c#像目标c中一样调度队列 [英] c# dispatch queues like in objective c

查看:254
本文介绍了c#像目标c中一样调度队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想模仿c#中的Objective-C分派队列的行为.我看到有一个任务并行库,但是我真的不明白如何使用它,希望能对它有一些解释.

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.

在目标c中,我将执行以下操作:

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;
  }];

}

这如何转换为c#风格的任务并行库?

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

有没有比较网站?

推荐答案

如果只想在后台线程上执行一些长时间运行的CPU密集型代码,当完成后,请在UI线程上处理结果,将Task.Run()await结合使用:

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);
}

AMethod()现在是一个async Task方法,这意味着它的调用方也必须是一个async方法.

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

这篇关于c#像目标c中一样调度队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆