Skip to content

Avoid state machine in InvokeAsync #12697

@HenKun

Description

@HenKun

In Control.InvokeAsync in

BeginInvoke(async () => await WrappedCallbackAsync().ConfigureAwait(false));
the async/await might be elided, at least it could be considered. This applies to both overloads accepting a Func<Task>.

According to Stephen Cleary this is a simple passthrough and does not harm to elide the keywords, but it's more efficient.

By not including these keywords, the compiler can skip generating the async state machine. This means that there are fewer compiler-generated types in your assembly, less pressure on the garbage collector, and fewer CPU instructions to execute.

However, it’s important to point out that each of these gains are absolutely minimal. There’s one fewer type, a handful of small objects saved from GC, and only a few CPU instructions skipped. The vast majority of the time, async is dealing with I/O, which completely dwarfs any performance gains. In almost every scenario, eliding async and await doesn’t make any difference to the running time of your application.

Recommended Guidelines
I suggest following these guidelines:

[...]
2. Do consider eliding when the method is just a passthrough or overload.

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions