I have the following scenario:
async void DoStuff() {
// ...
}
button1.Click += (s, p) => {
DoStuff();
};
I'm not sure what happens when I call an async void
method while the first call is still incomplete.
Will the call create a new thread everytime it is called or will the call destroy and override the previous thread created? Also, will the local method variables be shared if the former assumption is right?
EDITED:
I had misunderstood the async await
thing because in windows 8 apps, it behaves differently. If you thought that calling an async method was the same as creating a new thread like me, please read this clarifying aricle.
With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. Figure 2 illustrates that exceptions thrown from async void methods can't be caught naturally.
The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.
No, it does not. It MAY start another thread internally and return that task, but the general idea is that it does not run on any thread.
A Task returning async method can be awaited, and when the task completes, the continuation of the task is scheduled to run. A void returning async method cannot be awaited; it is a "fire and forget" method. It does work asynchronously, and you have no way of telling when it is done.
I'm not sure what happens when I call an async void method more than once at the same time
You mean if another call occurs while the first call is still incomplete (potentially "paused")? It will work just fine. There's no "overriding", no "destroying". You'll end up with another instance of the state machine (which is what the compiler builds for you).
The two state machines will have entirely separate local variables etc. Of course, only one of them can actually run at a time, unless somewhere in the async method you avoid capturing the context.
Don't forget that starting an async method doesn't start a new thread. Some async operations you start within the async method may start new threads, but that's a different matter. Nothing within the generated code creates a new thread.
No.
Async methods have nothing to do with threads.
Rather, an async method will execute its code on the caller's thread, exactly like a regular method call, until the first await
.
The code after each await
will run on the thread the the awaitable ran its callback on.
This depends on exactly what you're await
ing.
Typically, you'll be await
ing Task
objects, which by default run their callbacks on the UI thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With