Awaiting Tasks and Methods

Wait for things to finish, the async way

Posted by Rodrigo Castro on December 23, 2024

C# uses Task and async/await to run code asynchronously (in the background).

πŸƒβ€β™‚οΈ Awaiting a Task

1
2
3
4
5
async Task RunAsync()
{
    await Task.Delay(1000); // Wait 1 second
    Console.WriteLine("Finished waiting!");
}

πŸ’Ό Awaiting Async Methods

You can await any method that returns a Task or Task<T>.

1
2
3
4
5
6
7
8
9
10
11
async Task<int> GetNumberAsync()
{
    await Task.Delay(500);
    return 42;
}

async Task UseNumberAsync()
{
    int n = await GetNumberAsync();
    Console.WriteLine(n);
}

πŸ“ Why Await?

  • Keeps your app responsive.
  • Lets you write code that looks synchronous, but isn’t.

πŸ’‘ Try It!

Write a method that fetches data asynchronously (simulate with Task.Delay), then prints the result.

1
2
3
4
5
async Task<string> FetchDataAsync()
{
    await Task.Delay(1000);
    return "Data loaded";
}

Next: Handling async errors!