async and await are C# keywords for writing asynchronous code that reads like synchronous code. They let a method start a long-running operation, such as a database query or HTTP request, and pause without blocking the thread until the result arrives. Example: public async Task<Product?> GetProductAsync(int id, CancellationToken ct) { var product = await _db.Products.FindAsync([id], ct); // does not block the thread if (product is null) return null; product.Reviews = await _reviewsApi.GetAsync(id, ct); // another non-blocking wait return product; } How it works - async enables await inside the method and makes the compiler generate a state machine. - await on an incomplete task registers the remaining code as a continuation and returns control to the caller. The thread goes back to the pool (or keeps the UI responsive). - When the operation completes, the method resumes after the await, and the result or exception is delivered as if the code ran normally. - Async methods return Task, Task<T>, ValueTask<T>, or IAsyncEnumerable<T> for async streams. async void is only for event handlers. Benefits - Scalability for servers: threads are not wasted while waiting for I/O, so the same server can handle many more concurrent requests. - Responsiveness for UI apps: the interface does not freeze during network calls. - Readable code compared with callbacks or continuation chains. Common patterns - Parallel independent calls: await Task.WhenAll(task1, task2). - Timeouts and cancellation with CancellationToken and CancelAfter. - Async streams: await foreach (var item in GetItemsAsync()). Common mistakes - Blocking on async code with .Result or .Wait(), which risks deadlocks or thread-pool starvation. - Forgetting to await a task, which loses exceptions. - Using async for CPU-bound work and expecting it to run faster — async helps waiting, not computation. - Wrapping synchronous code in Task.Run inside ASP.NET Core requests. One-line summary: async/await lets your code wait efficiently — the work continues when the I/O completes, without holding a thread hostage in the meantime.
Ravindra Wadile · · 0 likes