❗ Avoid .Wait() and .Result in Async Contexts – Here’s Why
Calling .Wait() or .Result on a Task blocks the current thread until the Task completes.
In an async context (like a UI thread or ASP.NET request), this can cause a deadlock.
🧠 Why?
Async methods often capture the current synchronization context to resume on the same thread after an await.
But if that thread is blocked by .Wait() or .Result, the continuation cannot resume.
The result:
The Task is waiting to resume on a thread that's blocked waiting for the Task
➡️ Deadlock.
💥 Example: Deadlock in a Console App (simulating UI behavior)
public class DeadlockDemo
{
public static void Main()
{
Console.WriteLine("Starting...");
var result = GetData().Result; // ❌ This can deadlock in UI/ASP.NET
Console.WriteLine($"Result: {result}");
}
public static async Task<string> GetData()
{
await Task.Delay(1000); // Simulate async work
return "Hello from async!";
}
}
What happens?
In a real UI (WinForms/WPF) or ASP.NET context, Result can freeze the thread, causing a deadlock if the continuation needs to return to the UI thread.
✅ The Right Way: Use await
public class AsyncSafeDemo
{
public static async Task Main()
{
Console.WriteLine("Starting...");
var result = await GetData(); // ✅ Safe and non-blocking
Console.WriteLine($"Result: {result}");
}
public static async Task<string> GetData()
{
await Task.Delay(1000); // Simulate async work
return "Hello from async!";
}
}
Why this works:
await allows the thread to remain free while waiting for the Task. The continuation is scheduled properly without blocking.
❌ Avoid .Result or .Wait() in async contexts (can cause deadlocks).
✅ Use await to keep things async and non-blocking.
Top comments (0)