winforms icon indicating copy to clipboard operation
winforms copied to clipboard

Avoid state machine in InvokeAsync

Open HenKun opened this issue 1 year ago • 3 comments

In Control.InvokeAsync in https://github.com/dotnet/winforms/blob/17db32a122632f4e78b46d0a5b4aca4d1a60c0f7/src/System.Windows.Forms/src/System/Windows/Forms/Control_InvokeAsync.cs#L238 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.

HenKun avatar Dec 31 '24 06:12 HenKun

@HenKun:

Hey Henning,

thanks for reporting this as bugs - I will try to prioritize this, because it's a REALLY good catch, and I want this in as soon as possible.

Due to recent events, we need to reprioritize a series of tasks. Since I have a very strong feeling, you absolutely know what you're doing here, would you like to give it a shot and a submit a PR to get this fixed?

It would drastically increase the chances, to have this in for Preview 6 then, and ... das würde die WinForms community natürlich ganz enorm nach vorne bringen, weil die Async features natürlich immer wichtiger werden!

Mein ausdrückliches "Vielen Dank" für deine Hilfe hier!

Best

Klaus

PS: I hope I inferred your set of languages skills correctly for your last name! :-)

KlausLoeffelmann avatar May 17 '25 17:05 KlausLoeffelmann

@KlausLoeffelmann Hi Klaus,

mit deinen Schlussfolgerungen zur Sprache lagst du goldrichtig ;)

I opened a PR containing and justifying the changes. However, it needs rebase respectively conflict resolution which can't be done within the GitHub GUI weirdly, so I need to have a look tomorrow.

HenKun avatar May 20 '25 19:05 HenKun

Thanks for the PR, I will see that we can take it for Preview 6! @merriemcgaw FYI.

KlausLoeffelmann avatar Jun 04 '25 00:06 KlausLoeffelmann