Home >Backend Development >C++ >When Should You Use `await` Instead of `Task.Result` for Completed Tasks?

When Should You Use `await` Instead of `Task.Result` for Completed Tasks?

Susan Sarandon
Susan SarandonOriginal
2025-01-22 23:19:11199browse

When Should You Use `await` Instead of `Task.Result` for Completed Tasks?

await vs. Task.Result for Completed Tasks: Best Practices

The "Concurrency in C# Cookbook" demonstrates a pattern for handling completed tasks:

<code class="language-csharp">var completedTask = await Task.WhenAny(downloadTask, timeoutTask);
if (completedTask == timeoutTask)
  return null;
return await downloadTask;</code>

This code uses Task.WhenAny to determine whether downloadTask (an httpclient.GetStringAsync call) completes before timeoutTask (a Task.Delay operation).

Why use await downloadTask instead of simply returning downloadTask.Result? The reasons are crucial:

Exception Handling:

  • await avoids the complexities of AggregateException. Task.Result or Task.Wait() wrap exceptions within AggregateException, obscuring the root cause. Asynchronous code should ideally handle exceptions directly, making await the cleaner solution.

Deadlock Avoidance:

  • Using Task.Result or Task.Wait() within an asynchronous method can lead to deadlocks. await is designed for asynchronous contexts and prevents this common pitfall.

Best Practices Summary:

  • Favor await in asynchronous application code for better exception handling and deadlock prevention.
  • While Task.Result or Task.Wait() might be acceptable in utility code (with clear comments explaining the rationale), it's generally best avoided.
  • Task.Result and Task.Wait() can be considered for parallel task scenarios where synchronous blocking is acceptable and understood.

The above is the detailed content of When Should You Use `await` Instead of `Task.Result` for Completed Tasks?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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