How are async void calls made in C #?

If you declare event handlers as async void , will they be called synchronously or asynchronously using the .NET platform?

Ie, given the following code:

 async void myButton_click(object sender, EventArgs e) { do stuff await longRunning() do more stuff } 

Can I be sure that the line "do stuff" will be executed in the GUI thread?

+5
source share
2 answers

Event handlers will be called synchronously and will not wait (wait) until the event handler completes, but waits until the event handler returns.

If the previous sentence was confusing enough, I will try to explain it clearly. Asynchronous methods terminate when all waiting points are executed and the end of the method body is completed or any return statement is executed (ignoring an exception). But the asynchronous method returns as soon as you press the first wait statement for Task , which is not yet complete. In other words, an asynchronous method can return several times, but can only end once.

So now we know when the asynchronous method completes and returns. The event handler will assume that your method completed as soon as it returns not when it actually completed.

As soon as your event handler reaches the first await statement, it will return; if more methods are added to the same event handler, it will continue to execute without waiting for the asynchronous method to complete.

Yes, do stuff will be executed in the user interface thread if the user interface thread fires an event, and yes do more stuff will also be executed in the user interface thread until longRunning().ConfigureAwait(false) .

+9
source

They will be called just like any other async-await method is called:

 Click(this, EventArgs.Empty); 

Since this special event handler is an async method, the call will be executed synchronously until await is reached and the rest is continued. This means that do stuff runs synchronously in the GUI thread . The caller then proceeds without knowing that the async operation is not yet complete.

do more stuff will also run in the GUI thread, but for a different reason. SynchronizationContext in the GUI environment ensures that continuations will be sent to the same GUI thread unless you explicitly specify this using await longRunning().ConfigureAwait(false)

+4
source

Source: https://habr.com/ru/post/1208030/


All Articles