Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
// async/await fundamentals with HttpClient using System.Net.Http; using System.Net.Http.Json; // async Main — entry point can be async in modern C# // (the compiler wraps it in a Task automatically with top-level statements) var client = new HttpClient(); client.DefaultRequestHeaders.UserAgent.ParseAdd("CsharpDemo/1.0"); // Async method returning Task<T> static async Task<string> FetchAsync(HttpClient http, string url) { HttpResponseMessage response = await http.GetAsync(url); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } // Awaiting the result try { string body = await FetchAsync(client, "https://httpbin.org/get"); Console.WriteLine(body[..200]); // first 200 chars } catch (HttpRequestException ex) { Console.WriteLine($"HTTP error: {ex.StatusCode} — {ex.Message}"); } // Running multiple async operations concurrently with Task.WhenAll async Task<int[]> FetchCountsAsync() { var urls = new[] { "https://httpbin.org/get", "https://httpbin.org/ip" }; Task<string>[] tasks = urls .Select(url => FetchAsync(client, url)) .ToArray(); string[] results = await Task.WhenAll(tasks); return results.Select(r => r.Length).ToArray(); } int[] counts = await FetchCountsAsync(); Console.WriteLine($"Response sizes: {string.Join(", ", counts)}");
Result
Open