Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

"var myValue = DoSomethingAsync().ConfigureAwait(false).Result;"

In my view there should be a built-in keyword to do this right. It's too easy to get this wrong and even worse possible problems only show up rarely.



If this really needs to happen then I like .GetAwaiter().GetResult() instead of .Result to get the same exception behavior as await rather than the wrapped AggregateException that .Result throws. This is especially helpful if DoSomethingAsync sometimes throws synchronously rather than returning a task.


The reason there isn't a keyword is because its not possible to do it right. The example given is far from foolproof.


But there should be an easy way to do it right. Needing to call async functions from non-async code is not exactly an unusual thing. Or they need to make absolutely everything async which is also problematic, especially in terms of raw performance.


Well, you can put it into an extension method like this:

T SyncResult<T>(this Task<T> task){ return task.ConfigureAwait(false).Result; }

Same for ValueTask. It may already be implemented in the base .NET library as well.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: