Home > Backend Development > C++ > Await vs. Result: When Should You Use `await` Instead of `.Result` in C# Async Tasks?

Await vs. Result: When Should You Use `await` Instead of `.Result` in C# Async Tasks?

DDD
Release: 2025-01-22 22:51:09
Original
743 people have browsed it

Await vs. Result: When Should You Use `await` Instead of `.Result` in C# Async Tasks?

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>
Copy after login

Since downloadTask would have been completed without timeout, why do we need to do a second await instead of returning directly to downloadTask.Result?

Advantages of

await over .Result

The author highlights two main reasons for using await in preference to .Result (or Wait):

  1. Exception Handling: await does not wrap exceptions in AggregateException, providing a clearer exception handling mechanism.
  2. Avoid deadlocks: Using .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:

  • Asynchronous application code: Always use await.
  • Asynchronous Utility Library: May be used with .Result or Wait with caution and with adequate documentation.
  • Parallel task code: For non-asynchronous parallel tasks, .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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template