Task for void async
Context: For async methods that do not return a value, return Task. This allows the caller to await the operation.
using System.IO;using System.Threading.Tasks;
public class DataService{ public async Task SaveDataAsync(string data) { await File.WriteAllTextAsync("file.txt", data); }}
// Caller can await// await new DataService().SaveDataAsync("content");Why not void?
Section titled “Why not void?”Returning Task allows the caller to:
- Await completion.
- Handle exceptions (exceptions are captured in the task).
- Compose with other async operations.
Real-world usage example
Section titled “Real-world usage example”Event handlers in UI: Use async void for events, but for all other async methods without return value, use Task.
Example: Async guidelines recommend Task over void.