4 ms·
C# uses “implicit context switch” on its async/await as it captures the current SynchronizationContext by default. On WPF/winforms/UWP and classic ASP there is
by metaltyphoon 5y ago
C# uses “implicit context switch” on its async/await as it captures the current SynchronizationContext by default. On WPF/winforms/UWP and classic ASP there is one, so unless you other wise tell it, the await always comes back on the UI thread.
Console and ASP net core have null as their SynchronizationContext.
- jayd16 5y agoC# will not context switch until you yield execution with an await. There is some default continuation setup that will happen if you use the Task Parallel Library (where the context management is explicit but abstracted away inside the library) but that's a different thing.
- DaiPlusPlus 5y ago> it captures the current SynchronizationContext by default. Which results in the majority of async code, which doesn't run in a UI context, needing to spam `.ConfigureAwait(false)` everywhere. It's the most visible wart in C# today - and no end of requests for a more succint alternative: https://github.com/dotnet/csharplang/discussions/645 https://github.com/dotnet/csharplang/discussions/645
- jayd16 5y agoI mostly deal with UI code so of course I like it how it is but couldn't anyone create, say, a BackgroundTask<T> that extends Task where ConfigureAwait is defaulted to false? Seems like a clear way to add it to the method signature and inform the caller and solve the issue with minimal work. Does that not work?
- DaiPlusPlus 5y agoThat wouldn't be appropriate: whether or not execution should resume on the same context is the caller's responsibility, not that of the function you're calling. i.e. the same async method could be called from UI code and should resume on the UI thread immediately afterwards - or it could be called from library code - the method doesn't know that (nor does the person who wrote the method).
- jayd16 5y agoI see your point but in reality the callee did already make the decision by using Task/TPL. As a language C# leaves the continuation functionality to the specific awaitable implementation. It seems like the natural place to make a different choice. I do agree that I do not want to see it, though.