How does c# handle async void

邮差的信 提交于 2019-12-23 12:06:28

问题


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.

Recently I saw wpf code, that does something like that:

    public async void Execute(object parameter)
    {
        await ExecuteAsync(parameter);
    }

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?


回答1:


I explain how async void methods work - and why they should be avoided - in my Best Practices in Asynchronous Programming article.

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". :)

"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).

How does it work? How does this translate to aspnet?

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.




回答2:


Async void is only to be used for event handler/delegate comparability. that Execute is a event callback, likely from a DelegateCommand or similar.

The way it works is it treats it exactly the same as if you had a function that returned a Task but the caller never called await on that returned task.

On ASP.NET you are likely to never use async void and instead be using controllers that expose methods that return a Task<ActionResult>, use HostingEnviorment.QueueBackgroundWorkItem, or using functions that are wrapped up in a Page.RegisterAsyncTask in situations where you would have used async void in normal desktop programming.

public void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(LoadSomeData));
}


来源:https://stackoverflow.com/questions/41685636/how-does-c-sharp-handle-async-void

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!