Choice of await
and .Result
in C# asynchronous tasks
In Stephen Cleary's "C# Concurrent Programming Handbook", a technique caught my attention:
<code class="language-csharp">var completedTask = await Task.WhenAny(downloadTask, timeoutTask); if (completedTask == timeoutTask) return null; return await downloadTask;</code>
Since downloadTask
would have been completed without timeout, why do we need to do a second await
instead of returning directly to downloadTask.Result
?
await
over .Result
The author highlights two main reasons for using await
in preference to .Result
(or Wait
):
await
does not wrap exceptions in AggregateException
, providing a clearer exception handling mechanism. .Result
or Wait
within an asynchronous method may cause deadlocks or subtle runtime issues. User Guide
While the use of .Result
or Wait
is not completely prohibited, the following guidelines are recommended:
await
. .Result
or Wait
with caution and with adequate documentation. .Result
and Wait
are suitable. By following these guidelines, developers can improve exception handling, prevent deadlocks, and write more robust and maintainable asynchronous code.
The above is the detailed content of Await vs. Result: When Should You Use `await` Instead of `.Result` in C# Async Tasks?. For more information, please follow other related articles on the PHP Chinese website!