Quick Answer
Handle operation timeouts.
Understanding the Issue
Occurs when an operation exceeds its allotted time, common in network and async operations.
The Problem
This code demonstrates the issue:
Csharp
Error
var client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(1);
await client.GetAsync("slow-website.com"); // Throws
The Solution
Here's the corrected code:
Csharp
Fixed
// Solution 1: Catch and retry
try {
await client.GetAsync(url);
} catch (TimeoutException) {
// Retry logic
}
// Solution 2: Configure timeout per request
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await client.GetAsync(url, cts.Token);
// Solution 3: Use WhenAny with delay
var downloadTask = client.GetAsync(url);
var timeoutTask = Task.Delay(5000);
var completed = await Task.WhenAny(downloadTask, timeoutTask);
if (completed == timeoutTask) {
// Handle timeout
}
// Solution 4: Polly retry policy
var policy = Policy
.Handle<TimeoutException>()
.WaitAndRetryAsync(3, _ => TimeSpan.FromSeconds(1));
await policy.ExecuteAsync(() => client.GetAsync(url));
// Solution 5: Adjust timeout settings
client.Timeout = TimeSpan.FromSeconds(30);
Key Takeaways
Implement proper timeout handling and retry logic for unreliable operations.