Daniel San
Daniel San

Reputation: 2026

Does an async void method create a new thread everytime it is called?

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.

Upvotes: 5

Views: 4158

Answers (2)

SLaks
SLaks

Reputation: 887305

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 awaiting.
Typically, you'll be awaiting Task objects, which by default run their callbacks on the UI thread.

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1500055

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.

Upvotes: 8

Related Questions