Created
June 26, 2025 16:28
-
-
Save emonarafat/ffd2d66c298179796727cc83092dddd4 to your computer and use it in GitHub Desktop.
Avoid Task.Result — Async/Sync Mismatch in .NET Can Cause Deadlocks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
🛑 Avoid
Task.Result— Async/Sync Mismatch in .NET Can Cause DeadlocksThis Gist demonstrates a common trap in .NET: using
.Resultor.Wait()on async methods.It includes:
async/awaitapproachUse this as a reference in code reviews, training, or interview prep.
🔗 Full article:
Task.ResultWill Wreck Your App — and Your Interview