Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

How does c# handle async void

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...