Skip to content

Task (no result)

Context: Task represents an asynchronous operation that does not return a value. It is the equivalent of void for async methods.

using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
public class Example
{
public async Task DownloadFileAsync(string url)
{
using HttpClient client = new HttpClient();
string content = await client.GetStringAsync(url);
await File.WriteAllTextAsync("file.txt", content);
}
}
// Calling the method
// await new Example().DownloadFileAsync("https://example.com/data");
  • The method still returns a Task object that can be awaited.
  • Exceptions thrown inside the method are captured in the returned Task.

Logging asynchronously: Writing log entries to a file or database without blocking the main flow.

Example: In ASP.NET Core middleware, you often await next() which returns a Task.