Asynchronous Programming and Threads

Improve scalability with async and multithreading

Posted by Rodrigo Castro on January 24, 2025

Async programming lets your apps handle more work with fewer resources.

๐Ÿ”„ Why Async?

  • Frees up threads while waiting for I/O (web requests, file I/O)
  • Improves app scalability and responsiveness

๐Ÿš€ Basic Example

1
2
3
4
5
public async Task<string> DownloadAsync(string url)
{
    using var client = new HttpClient();
    return await client.GetStringAsync(url);
}

๐Ÿงต Working with Threads

  • Use the Thread class for low-level multithreading:
1
2
var thread = new Thread(() => Console.WriteLine("Running in a thread!"));
thread.Start();

๐Ÿ—๏ธ Tasks and Parallelism

  • Use Task and async/await for most scenarios.
  • Use Parallel.ForEach for CPU-bound work.

โš ๏ธ Tips

  • Avoid mixing threads and async unless necessary.
  • Use ConfigureAwait(false) in libraries to avoid deadlocks.

Next: Using async and await!