How to Handle Asynchronous Programming with Async/Await in C#?
This example fetches data from a URL asynchronously without blocking the main thread, demonstrating the use of async
and await
.
By providing detailed Q&A like these on your blog, you can offer valuable solutions to your readers, helping them tackle complex SQL and C# challenges effectively.
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string url = "https://api.github.com/repos/dotnet/roslyn";
string result = await FetchDataAsync(url);
Console.WriteLine(result);
}
public static async Task<string> FetchDataAsync(string url)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.UserAgent.TryParseAdd("request");
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
}
}
Comments
Post a Comment