Home >Backend Development >C++ >`.GetAwaiter().GetResult()` vs. `Task.Result`: When Should You Use Each?

`.GetAwaiter().GetResult()` vs. `Task.Result`: When Should You Use Each?

Susan Sarandon
Susan SarandonOriginal
2025-01-24 11:51:10221browse

`.GetAwaiter().GetResult()` vs. `Task.Result`: When Should You Use Each?

Task.GetAwaiter().GetResult() vs. Task.Result: When to use which one?

The need to execute asynchronous methods synchronously in code is very common. This can be achieved via the Task or .GetAwaiter().GetResult() attributes of .Result. However, it is crucial to understand the nuances and potential shortcomings of both approaches.

Task.GetAwaiter().GetResult()

Calling Task on .GetAwaiter().GetResult() will directly retrieve its result or throw any unobserved exception. This behavior is better than .Wait() and .Result because it ensures propagation of the original exception without encapsulating it in AggregateException.

However, it is important to note that .GetAwaiter().GetResult(), like .Wait() and .Result, has the same risk of deadlock and thread pool resource exhaustion.

Task.Result

The

attribute of Task.Result will also retrieve its result and will throw TaskCanceledException if the task is cancelled. However, any other unobserved exceptions in the asynchronous operation will be caught and wrapped in AggregateException.

When to use which method

Although .GetAwaiter().GetResult() has the advantage of exception propagation, it is strongly recommended to avoid synchronous blocking of asynchronous tasks whenever possible. This approach can lead to deadlocks and resource exhaustion. Instead, consider writing fully asynchronous code using the async/await mechanism to avoid these problems.

The above is the detailed content of `.GetAwaiter().GetResult()` vs. `Task.Result`: When Should You Use Each?. 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