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
andasync/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!