C#如何处理异步void [英] How does c# handle async void
问题描述
我通常对Web服务器进行编程,起初我以为必须有连续的方法链返回任务,因此将堆栈塞满可能会询问数据库是否已完成.
I generally program webservers and at first I thought that there must be continuous chain of methods that return task, so stuff up the stack may ask database if it is done.
最近我看到了wpf代码,该代码类似于:
Recently I saw wpf code, that does something like that:
public async void Execute(object parameter)
{
await ExecuteAsync(parameter);
}
在事件处理程序中调用. UI似乎是响应式的,所以我认为它确实有效.它是如何工作的?这如何转换为aspnet?
Called in event handler. UI seems to be responsive, so I guess it does work. How does it work? How does this translate to aspnet?
推荐答案
async void
has the same semantics as async Task
, except for exceptions. An async void
method will capture the current SynchronizationContext
at the beginning of the method, and any exceptions from that method will be captured and raised directly on that captured context. In the most common scenarios, this will cause an application-level exception, usually a crash. Some people call async void
methods "fire-and-forget", but because of their exceptional behavior, I prefer "fire-and-crash". :)
避免异步无效"是一般准则,但有一个明显的例外:事件处理程序(或在逻辑上是事件处理程序的项,例如ICommand.Execute
实现).
"Avoid async void" is the general guideline, with one notable exception: event handlers (or items that are logically event handlers, such as ICommand.Execute
implementations).
它如何工作?这如何转换为aspnet?
How does it work? How does this translate to aspnet?
它的工作原理与其他任何async
方法一样.平台的主要区别在于,当async
方法完成时,UI线程不需要知道. ASP.NET需要知道这一点,因此它知道何时发送请求,但是UI不需要知道async
方法何时完成.因此async void
起作用.仍然最好避免,因为调用代码通常 需要知道它何时完成.
It works just like any other async
method. The main platform difference is that the UI thread doesn't need to know when the async
method completes. ASP.NET needs to know that so it knows when to send the request, but the UI has no need to know when the async
method completes. So async void
works. It's still best avoided, because the calling code usually does need to know when it completes.
这篇关于C#如何处理异步void的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!