Quick Answer
Write non-blocking code with async/await.
Understanding the Issue
The async/await pattern simplifies asynchronous programming. async marks a method as asynchronous, await pauses execution until the awaited task completes without blocking the thread.
The Problem
This code demonstrates the issue:
Csharp
Error
// Need to call async method without blocking
The Solution
Here's the corrected code:
Csharp
Fixed
public async Task<string> FetchDataAsync()
{
using HttpClient client = new();
return await client.GetStringAsync("https://api.example.com");
}
// Consuming
public async void Button_Click(object sender, EventArgs e)
{
try {
string data = await FetchDataAsync();
Console.WriteLine(data);
}
catch (Exception ex) {
Console.WriteLine($"Error: {ex.Message}");
}
}
Key Takeaways
Always await async calls and handle exceptions properly.