4 ms·
> An often-asked question is how to synchronously wait on an async method. The usual answer is "don't do it" like it solves anything. But async methods return a
by Hawxy 5y ago
> An often-asked question is how to synchronously wait on an async method. The usual answer is "don't do it" like it solves anything. But async methods return a Task and the official examples for tasks tell you explicitly to use Wait() method to wait on a task.
This is mostly the fault of the TPL documentation being written eons ago. I'd recommend David Fowler's async guidance for a modern take:
https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md#avoid-using-taskresult-and-taskwait https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/b...
`.GetAwaiter().GetResult()` is generally considered the best way to do it if you must do sync over async, but in modern code it should almost never be required.
> I tried to convert a project to NRTs and gave up, reverted everything. I haven't seen a NRE in years :p NRTs introduce a lot of edge cases, with a lot of syntactic noise to cover them and still guarantees nothing (unlike a proper Optional type would).
I've been working on updating a number of libraries to support NRTs with success. I find it's a good for developer ergonomics so you know what can return/be null and what cannot without needing it laid out within xml comments or documentation. ASP.NET Core 5+ will also automatically validate request payloads depending on a type being nullable or not. NRTs will be enabled in project templates by default with .NET 6.
- zvrba 5y ago> I'd recommend David Fowler's async guidance for a modern [...] .GetAwaiter().GetResult() Yeah, you should add to that `ConfigureAwait(false)`. That you need a long webpage about `async` and that the official documentation on Task doesn't apply kind of drives the point home. They've botched the design of async. Yes, it works "well enough" in 95% of cases, but the remaining 5% is a mine-field.