C# Asynchronous Programming

C# Async Methods

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.

```cs
public async Task<string> FetchDataAsync()
{
// Simulate an asynchronous operation
await Task.Delay(1000);
return "Data fetched successfully!";
}
```

C# CancellationToken Usage

The 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.

```cs
using 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 seconds
Task.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 work
Console.WriteLine($"Iteration {i+1} complete.");
}
}
}
```

C# Async Exception Handling

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 exceptions
foreach (var exception in ex.InnerExceptions)
{
Console.WriteLine(exception.Message);
}
}
catch (Exception ex)
{
// Handle any other exception
Console.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);
}
}

C# Async Coordination

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.WhenAll
async 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.WhenAny
async 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.");
}

C# Async Programming

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.

```csharp
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
Task<int> resultTask = ComputeAsync();
// Do other work while waiting
Console.WriteLine("Working...");
int result = await resultTask;
Console.WriteLine($"Result: {result}");
}
static async Task<int> ComputeAsync()
{
await Task.Delay(1000); // Simulates a delay
return 42;
}
}
```

C# Await Keyword

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.

```cs
using 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
}
}
}
```

C#: 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.

```cs
using System;
using System.Threading.Tasks;
public class Example
{
public static async Task<int> FetchDataAsync()
{
await Task.Delay(1000); // Simulate network delay
return 42; // Simulated result
}
public static async Task Main(string[] args)
{
int result = await FetchDataAsync();
Console.WriteLine($"Fetched data: {result}");
}
}
```

Asynchronous Programming C#

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.

C# TAP Model

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.

Learn more on Codecademy