⚡ 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 Task<string> GetUserAsync()
{
var response = await httpClient
.GetStringAsync("/api/user");
return response;
}
📝 Async Examples
// Basic async method
public async Task<User> GetUserAsync(int id)
{
return await _dbContext.Users.FindAsync(id);
}
// Error handling
public async Task<User> 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<UserSummary> 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<User> 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#.”
