Quick Answer
Properly await async methods.
Understanding the Issue
Occurs when awaiting non-task values. Only methods returning Task/Task<T> can be awaited. void methods should return Task.
The Problem
This code demonstrates the issue:
Csharp
Error
async void BadAsync() {
await Task.Delay(100);
return "result"; // Error
}
The Solution
Here's the corrected code:
Csharp
Fixed
// Solution 1: Return Task<T>
async Task<string> GoodAsync() {
await Task.Delay(100);
return "result";
}
// Solution 2: Proper void handling
async Task DoWorkAsync() {
await Task.Run(() => {/* work */});
}
// Solution 3: Consume properly
public async Task Process() {
string result = await GoodAsync();
}
Key Takeaways
Always return Task/Task<T> from async methods.