【发布时间】:2019-01-12 08:09:55
【问题描述】:
我已经阅读了来自 John Thiriet 的关于制作“一劳永逸”方法的博文。我确实实现了他的扩展方法,虽然我在使用它时遇到了错误。
示例代码如下:
public async Task<ActionResult> Index()
{
/*
a lot of work here
some sync services called, some awaits to async services
*/
// here I wanted to call logging service using "fire and forget",
// because I don't really care about it,
// and I don't need to wait for it to show the page for user
_logService.LogAsync(obj).FireAndForgetSafeAsync();
return RedirectToAction("Summary");
}
这篇博文的方法如下:
public static class TaskUtilities
{
#pragma warning disable RECS0165 // Asynchronous methods should return a Task instead of void
public static async void FireAndForgetSafeAsync(this Task task, IErrorHandler handler = null)
#pragma warning restore RECS0165 // Asynchronous methods should return a Task instead of void
{
try
{
await task;
}
catch (Exception ex)
{
handler?.HandleError(ex);
}
}
}
代码使An asynchronous module or handler completed while an asynchronous operation was still pending 异常。我知道这是因为日志记录代码,但我不知道为什么。当我在Index 和await LogAsync 中尝试捕获时,它工作正常(也可以进行“慢”调试)。如何处理此代码以正常工作?我们可以使用等待其他方法在控制器中制作这样的扩展方法以使某些操作“一劳永逸”吗?有人可以向我解释什么是真正的错误以及为什么它不起作用?类似的线程并没有帮助我解释我的问题。谢谢。
【问题讨论】:
-
这是否解决了您的问题? stackoverflow.com/a/28806198/1149773。您需要使用
HostingEnvironment.QueueBackgroundWorkItem
标签: asp.net .net asynchronous model-view-controller async-await