c# dispatch queues like in objective c

江枫思渺然 提交于 2019-12-04 13:23:20

问题


I want to mimic the behavior of objective-c dispatch queues in c#. I see that there is a task parallel library but I really don't understand how to use it and was hoping to get some explanation on how.

In objective c i would do something like:

-(void)doSomeLongRunningWorkAsync:(a_completion_handler_block)completion_handler
{
 dispatch_async(my_queue, ^{
   result *result_from_long_running_work = long_running_work();
   completion_handler(result_from long_running_work);
 });
}

-(void)aMethod
{
  [self doSomeLongRunningWorkAsync:^(result *) { // the completion handler
    do_something_with_result_from_long_running_async_method_above;
  }];

}

How is this translated into c# style task parallel library?

Any comparison sites?


回答1:


If all you want is to execute some long-running CPU-intensive code on a background thread, and when it's done, process the result on the UI thread, use Task.Run() in combination with await:

async Task AMethod()
{
    var result = await Task.Run(() => LongRunningWork());
    DoSomethingWithResult(result);
}

The AMethod() is now an async Task method, which means its caller also has to be an async method.



来源:https://stackoverflow.com/questions/17259634/c-sharp-dispatch-queues-like-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!