⚡ Async/Await = High Performance
Async/await can hurt performance if misused. Best practices ensure maximum performance and scalability.
📝 Performance Best Practices
// Avoid async void public async Task ProcessAsync() // Good public async void ProcessAsync() // Bad // ConfigureAwait for libraries public async TaskGetDataAsync() { return await _httpClient.GetStringAsync(url) .ConfigureAwait(false); // Good for libraries } // Parallelize independent operations public async Task GetDashboardAsync() { var usersTask = GetUsersAsync(); var ordersTask = GetOrdersAsync(); var statsTask = GetStatsAsync(); await Task.WhenAll(usersTask, ordersTask, statsTask); return new DashboardData { Users = usersTask.Result, Orders = ordersTask.Result, Stats = statsTask.Result }; } // Use ValueTask for frequently called async methods public async ValueTask GetCountAsync() { // Use ValueTask when result is often cached if (_cachedCount.HasValue) return _cachedCount.Value; return await GetCountFromDatabaseAsync(); }
🎯 Common Pitfalls
// Avoid synchronous over async public async TaskGetDataAsync() { // Bad: Blocks thread return _httpClient.GetStringAsync(url).Result; } // Use proper cancellation public async Task GetDataWithTimeoutAsync(CancellationToken cancellationToken) { using var cts = CancellationTokenSource .CreateLinkedTokenSource(cancellationToken); cts.CancelAfter(TimeSpan.FromSeconds(30)); return await _httpClient.GetStringAsync(url, cts.Token); } // Avoid mixing sync and async public async Task ProcessDataAsync() { // Bad: Sync over async var data = GetDataSync(); await ProcessAsync(data); // Good: Async all the way var data = await GetDataAsync(); await ProcessAsync(data); } // Use proper exception handling public async Task GetDataWithRetryAsync() { int retryCount = 0; while (retryCount < 3) { try { return await GetDataAsync(); } catch (Exception) when (retryCount < 2) { retryCount++; await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, retryCount))); } } throw new Exception("Failed after 3 retries"); }
💡 Async Performance Tips
- Use ConfigureAwait(false) in libraries
- Parallelize independent operations
- Use ValueTask for cached results
- Implement proper cancellation
- Avoid async void
Async/await best practices are essential for building high-performance, scalable applications.
