⚡ Async/Await = Responsive Apps
Blocking calls freeze UI. Async/Await makes I/O operations non-blocking. Responsive, scalable.
❌ Synchronous
public void GetUser()
{
var response = httpClient
.GetStringAsync("/api/user").Result;
}
✅ Asynchronous
public async TaskGetUserAsync() { var response = await httpClient .GetStringAsync("/api/user"); return response; }
📝 Async Examples
// Basic async method public async TaskGetUserAsync(int id) { return await _dbContext.Users.FindAsync(id); } // Error handling public async Task GetUserWithErrorAsync(int id) { try { return await _dbContext.Users.FindAsync(id); } catch (Exception ex) { _logger.LogError(ex, "Error getting user"); throw; } } // Parallel operations public async Task GetUserSummaryAsync(int userId) { var userTask = _userService.GetUserAsync(userId); var ordersTask = _orderService.GetUserOrdersAsync(userId); var reviewsTask = _reviewService.GetUserReviewsAsync(userId); await Task.WhenAll(userTask, ordersTask, reviewsTask); return new UserSummary { User = userTask.Result, Orders = ordersTask.Result, Reviews = reviewsTask.Result }; } // Cancellation public async Task GetUserWithCancellationAsync( int id, CancellationToken cancellationToken) { return await _dbContext.Users .FindAsync(new object[] { id }, cancellationToken); } // Async Tips - Use async for I/O operations - Avoid async void (except events) - Use ConfigureAwait(false) in libraries - Handle exceptions properly - Use CancellationToken for timeouts
💡 Async Tips
- Use async for I/O operations
- Avoid async void (except events)
- Use ConfigureAwait(false) in libraries
- Handle exceptions properly
- Use CancellationToken for timeouts
“Async/Await makes apps responsive. No more frozen UI. Essential for modern C#.”
