c# dispatch queues like in objective c

2019-03-21 05:56发布

问题:

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.