Async / Await
Fundamental Concepts of Asynchronous Programming
Asynchronous programming allows an application to perform
multiple tasks at the same time without blocking the main thread.
In C#, the async keyword is used to mark a method as
asynchronous, while await is used to wait for the completion
of a task.
Benefits:
- Improves application performance and responsiveness.
- Allows executing I/O (input/output) operations without blocking the main flow.
- Makes it easier to write more readable code compared to traditional callbacks.
Basic Example
public async Task<string> GetDataAsync()
{
await Task.Delay(2000); // Simulates an asynchronous process
return "Data obtained";
}
Practical Exercises with async & await
- Create a method that waits for 3 seconds and then returns a message in the console.\
- Make an asynchronous call to a public API using
HttpClientand display the result.\ - Execute multiple asynchronous tasks in parallel and combine their results.
Task Management (Tasks)
The Task class represents an asynchronous operation that can return a
result.
There are different ways to declare and use tasks in C#.
Example with simple Task
public async Task SimpleProcess()
{
await Task.Delay(1000);
Console.WriteLine("Process completed");
}
Task Examples with Different Return Types
Task<IEnumerable<string>>
public async Task<IEnumerable<string>> GetNamesAsync()
{
await Task.Delay(500);
return new List<string> { "Ana", "Luis", "Carlos" };
}
Task<Dictionary<int, string>>
public async Task<Dictionary<int, string>> GetDictionaryAsync()
{
await Task.Delay(500);
return new Dictionary<int, string>
{
{ 1, "One" },
{ 2, "Two" },
{ 3, "Three" }
};
}
Task<object>
public async Task<object> GetObjectAsync()
{
await Task.Delay(500);
return new { Id = 1, Name = "Example" };
}
Task<(int, string)>
public async Task<(int, string)> GetTupleAsync()
{
await Task.Delay(500);
return (1, "Data");
}
Task<int>
public async Task<int> CalculateSumAsync(int a, int b)
{
await Task.Delay(500);
return a + b;
}