Asynchronous methods in C# are defined using the async
keyword, allowing non-blocking code execution. They return Task
or Task<T>
for handling asynchronous operations.
```cspublic async Task<string> FetchDataAsync(){// Simulate an asynchronous operationawait Task.Delay(1000);return "Data fetched successfully!";}```
CancellationToken
UsageThe CancellationToken
in C# allows for cancelling asynchronous tasks gracefully. It is often passed to tasks or operations that support cancellation, enabling them to check for termination requests and return early if needed, ensuring resource efficiency and responsive applications.
```csusing System;using System.Threading;using System.Threading.Tasks;class Program {static async Task Main(string[] args) {using var cts = new CancellationTokenSource();// Simulate user cancellation after 2 secondsTask.Run(() => {Thread.Sleep(2000);cts.Cancel();});Console.WriteLine("Task starting...");try {await RunTaskAsync(cts.Token);} catch (OperationCanceledException) {Console.WriteLine("Task cancelled.");}}static async Task RunTaskAsync(CancellationToken token) {for (int i = 0; i < 5; i++) {token.ThrowIfCancellationRequested();await Task.Delay(1000); // Simulate workConsole.WriteLine($"Iteration {i+1} complete.");}}}```
Handling exceptions in C# asynchronous code is pivotal. Use try...catch
blocks within async methods to catch exceptions. AggregateException
is used when multiple exceptions are thrown concurrently in tasks. Managing these properly ensures robust and reliable applications.
using System;using System.Threading.Tasks;class Program{static async Task Main(string[] args){try{await ThrowExceptionsAsync();}catch (AggregateException ex){// Handle multiple exceptionsforeach (var exception in ex.InnerExceptions){Console.WriteLine(exception.Message);}}catch (Exception ex){// Handle any other exceptionConsole.WriteLine($"Caught Exception: {ex.Message}");}}static async Task ThrowExceptionsAsync(){var task1 = Task.Run(() => throw new InvalidOperationException("Invalid operation."));var task2 = Task.Run(() => throw new ArgumentException("Invalid argument."));await Task.WhenAll(task1, task2);}}
In C#, manage concurrent operations using Task.WhenAll
and Task.WhenAny
. These methods allow running multiple operations parallely and syncing their outcomes effectively.
// Example of using Task.WhenAllasync Task PerformTasksConcurrentlyAsync() {var task1 = Task.Delay(2000);var task2 = Task.Delay(1000);await Task.WhenAll(task1, task2);Console.WriteLine("Both tasks have completed.");}// Example of using Task.WhenAnyasync Task PerformAnyTaskCompletionAsync() {var task1 = Task.Delay(2000);var task2 = Task.Delay(1000);var firstCompletedTask = await Task.WhenAny(task1, task2);Console.WriteLine("A task has completed first.");}
Asynchronous programming in C# allows your application to execute tasks without blocking the main thread. This enhances responsiveness and optimizes resource usage. By using keywords like async
and await
, functions can run independently of the main execution flow, improving performance.
```csharpusing System;using System.Threading.Tasks;class Program{static async Task Main(string[] args){Task<int> resultTask = ComputeAsync();// Do other work while waitingConsole.WriteLine("Working...");int result = await resultTask;Console.WriteLine($"Result: {result}");}static async Task<int> ComputeAsync(){await Task.Delay(1000); // Simulates a delayreturn 42;}}```
The await
keyword in C# allows you to work with asynchronous methods efficiently. This keyword supports non-blocking task completion, improving application performance by not holding the executing thread.
```csusing System;using System.Threading.Tasks;namespace AsyncExample {class Program {static async Task Main(string[] args) {Console.WriteLine("Task started");await CompleteTaskAsync();Console.WriteLine("Task completed");}static async Task CompleteTaskAsync() {await Task.Delay(2000); // Simulates a long-running task}}}```
The Task<T>
represents an asynchronous operation in C# that returns a value of type T
. It allows you to run tasks concurrently, handle task results, and catch exceptions efficiently. This enhances application responsiveness.
```csusing System;using System.Threading.Tasks;public class Example{public static async Task<int> FetchDataAsync(){await Task.Delay(1000); // Simulate network delayreturn 42; // Simulated result}public static async Task Main(string[] args){int result = await FetchDataAsync();Console.WriteLine($"Fetched data: {result}");}}```
In C#, asynchronous programming focuses on minimizing blocking operations to improve application performance. Key considerations include proper exception handling and effective task composition. Using async/await helps seamlessly manage asynchronous code, allowing functions to be interrupted and resumed efficiently.
The Task-based Asynchronous Pattern (TAP) in C# offers a standard way to handle asynchronous operations. TAP allows developers to write asynchronous code that is both easy to read and maintain. By utilizing Task
and Task<T>
, TAP simplifies working with asynchronous operations.