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:
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:
await
in asynchronous application code for better exception handling and deadlock prevention.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!