csharp / intermediate
Snippet
Asynchronous Programming with Tasks
Using async/await allows the application to remain responsive during I/O-bound operations by yielding control back to the caller while waiting for the task to complete.
snippet.csharp
1
2
3
4
5
6
public async Task<string> DownloadDataAsync(string url){using var client = new HttpClient();string result = await client.GetStringAsync(url);return result.Trim();}
Breakdown
1
public async Task<string>
The 'async' modifier enables the 'await' keyword and wraps the return type in a Task.
2
await client.GetStringAsync(url)
Suspends the method execution until the asynchronous operation completes, without blocking the thread.