Skip to content

Instantly share code, notes, and snippets.

@emonarafat
Created June 26, 2025 16:28
Show Gist options
  • Select an option

  • Save emonarafat/ffd2d66c298179796727cc83092dddd4 to your computer and use it in GitHub Desktop.

Select an option

Save emonarafat/ffd2d66c298179796727cc83092dddd4 to your computer and use it in GitHub Desktop.
Avoid Task.Result — Async/Sync Mismatch in .NET Can Cause Deadlocks
# TaskResultDeadlockExample.cs
// ❌ Anti-pattern: Mixing sync + async causes deadlocks
public class UserService
{
public string GetUserName(Guid id)
{
var client = new HttpClient();
// This will block the thread and can cause deadlocks in ASP.NET or UI apps
return client.GetStringAsync($"https://api.example.com/user/{id}").Result;
}
}
// ✅ Proper async approach: async all the way
public class UserServiceAsync
{
public async Task<string> GetUserNameAsync(Guid id)
{
var client = new HttpClient();
return await client.GetStringAsync($"https://api.example.com/user/{id}");
}
}
// Usage
public async Task Main()
{
var service = new UserServiceAsync();
var name = await service.GetUserNameAsync(Guid.NewGuid());
Console.WriteLine(name);
}
@emonarafat
Copy link
Author

🛑 Avoid Task.Result — Async/Sync Mismatch in .NET Can Cause Deadlocks

This Gist demonstrates a common trap in .NET: using .Result or .Wait() on async methods.
It includes:

  • ❌ A blocking example that can deadlock your app (especially in ASP.NET, WinForms, or WPF)
  • ✅ The correct async/await approach
  • 🧠 A golden rule: If it starts async, keep it async.

Use this as a reference in code reviews, training, or interview prep.

🔗 Full article: Task.Result Will Wreck Your App — and Your Interview

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment