Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Avoid state machine in InvokeAsync #12697

Open
HenKun opened this issue Dec 31, 2024 · 0 comments
Open

Avoid state machine in InvokeAsync #12697

HenKun opened this issue Dec 31, 2024 · 0 comments
Assignees

Comments

@HenKun
Copy link

HenKun commented Dec 31, 2024

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.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants