dotnet / docs

This repository contains .NET Documentation.
https://learn.microsoft.com/dotnet
Creative Commons Attribution 4.0 International
4.25k stars 5.89k forks source link

How to wait Tasks when unable to await? #37040

Open seppo498573908457 opened 1 year ago

seppo498573908457 commented 1 year ago

Eventually we run into a scenario, where we cannot go async/await for the full call stack. It's unclear what to do in such case, please help by extending this documentation.

What we run into:

The internet is not helpful in giving a silver bullet. We need working code, not fancy theories.


Document Details

Do not edit this section. It is required for learn.microsoft.com ➟ GitHub issue linking.

BillWagner commented 1 year ago

Adding @stephentoub

GetAwaiter().GetResult() is the best of the options I know of.

stephentoub commented 1 year ago

The internet is not helpful in giving a silver bullet

There is no silver bullet. The definition of the problem you've outlined is you need to invoke an asynchronous operation and you need that operation to complete before you allow the current thread to make forward progress. That necessarily means blocking the current thread.

https://devblogs.microsoft.com/pfxteam/should-i-expose-synchronous-wrappers-for-asynchronous-methods/

seppo498573908457 commented 1 year ago

Thanks for the quick replies. I've read the linked blog post and many others, they do well advertising the parallel programming.

Just to be clear, the asyncness has to eventually be waited somewhere, so blocking may be unavoided and that's fine. But the real issue here is minimizing "downtime" (like when UI responsiveness is affected) and avoiding deadlocks without getting unnecessary performance hits. On the internet there are many sources that contradict each other, some are outdated. It would be easier for everyone, if there was a clear documentation about how to properly wait and sync with tasks when awaiting is not an option. Better yet, that would rank first on search results, like most on MSDN.

BillWagner commented 1 year ago

I'll leave this in the backlog as an enhancement.

I think the best fix is to link to the various blog posts that point out the pitfalls with this scenario, and how to minimize the risk.

I'd prefer keeping those actions a couple clicks away because there isn't a general solution that doesn't have risks.