我想模仿c#中objective-c dispatch队列的行为。我看到有一个任务并行库,但我真的不明白如何使用它,并希望得到一些解释如何。
在目标c中,我会做类似的事情:
-(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#style任务并行库?
任何比较网站?
答案 0 :(得分:1)
如果您只想在后台线程上执行一些长时间运行的CPU密集型代码,并在完成后,在UI线程上处理结果,请将Task.Run()
与await
结合使用:
async Task AMethod()
{
var result = await Task.Run(() => LongRunningWork());
DoSomethingWithResult(result);
}
AMethod()
现在是async Task
方法,这意味着其调用者也必须是async
方法。