【发布时间】:2016-02-23 09:42:42
【问题描述】:
我正在努力解决如何在异步方法的世界中执行一些非常长时间运行的后台处理。
使用来自Stephen Cleary's blog 的词汇,我有兴趣在await 之后启动“委托任务” - 执行“承诺任务”。我想尽快返回承诺的值,并让委托任务在后台继续执行。
为了处理 un-await-ed 委托任务中的异常,我将使用仿照 the one described here. 建模的异常处理延续
public async Task<int> ComplexProcessAsync()
{
...
int firstResult = await FirstStepAsync();
// THE COMPILER DOESN'T LIKE THIS
Task.Run(() => VeryLongSecondStepIDontNeedToWaitFor(firstResult)).LogExceptions();
return firstResult;
}
由于VeryLongSecondStep...() 可能需要很多分钟,并且其结果完全可以通过副作用(例如出现在数据库中的记录)来观察,所以我reeeaaalllyy想await它。
但正如所指出的,编译器不喜欢这样。它警告"Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call."
我可以忽略警告,但我觉得我没有以“正确”的方式执行此操作。那么正确的方法是什么?
谢谢!
【问题讨论】:
-
您是否在 ASP.NET 应用程序中执行此操作?
-
@WilliamXifaras 这有关系吗?我知道 SynchronizationContext 和 TaskScheduler 可能不同,但这有意义吗?
-
重要的是我为您提供了一个适用于 ASP.NET 的选项。
-
@WilliamXifaras 我的应用程序是一个自托管的 Web API。
标签: c# .net async-await