⚡ TAP = Asynchronous Programming
Async is essential. TAP is the standard pattern. Async/await, Task, Task
📝 TAP Basics
// Basic async method public async TaskGetDataAsync() { using var client = new HttpClient(); var result = await client.GetStringAsync("https://api.example.com/data"); return result; } // Async with error handling public async Task GetUserAsync(int id) { try { var response = await _httpClient.GetAsync($"/api/users/{id}"); response.EnsureSuccessStatusCode(); var json = await response.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize (json); } catch (Exception ex) { _logger.LogError(ex, "Error getting user {Id}", id); throw; } } // Async void (avoid, except for events) public async void Button_Click(object sender, EventArgs e) { await DoWorkAsync(); }
🎯 Advanced TAP
// Multiple async operations (parallel) public async TaskGetUserSummaryAsync(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); } // Retry pattern public async Task RetryAsync ( Func > operation, int maxRetries = 3) { for (int i = 0; i < maxRetries; i++) { try { return await operation(); } catch (Exception) when (i < maxRetries - 1) { await Task.Delay(1000 * (i + 1)); } } return await operation(); } // Timeout public async Task FetchWithTimeoutAsync(string url, int timeoutMs = 5000) { using var cts = new CancellationTokenSource(timeoutMs); try { using var client = new HttpClient(); return await client.GetStringAsync(url, cts.Token); } catch (OperationCanceledException) { throw new TimeoutException($"Request timed out after {timeoutMs}ms"); } }
💡 TAP Tips
- Use async for I/O operations
- Avoid async void (except events)
- Use CancellationToken for timeouts
- Use Task.WhenAll for parallel
- Handle exceptions properly
“TAP is the async standard. Async/await, Task, Task
. Essential for modern C#.”
