我想在 C# 中模仿 Objective-C 调度队列的行为。我看到有一个任务并行库,但我真的不明白如何使用它,并希望得到一些关于如何使用它的解释。
在目标 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#风格的任务并行库的?
有比较网站吗?
如果您只想在后台线程上执行一些长时间运行的 CPU 密集型代码,并在完成后在 UI 线程上处理结果,请使用Task.Run()
结合await
:
async Task AMethod()
{
var result = await Task.Run(() => LongRunningWork());
DoSomethingWithResult(result);
}
The AMethod()
现在是一个async Task
方法,这意味着它的调用者也必须是async
method.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)