Search⌘ K
AI Features

Solution: Shipping API Timeout Fallback

Explore how to implement a timeout fallback for a Shipping API in C# using asynchronous programming. Understand how to await tasks with a timeout, catch exceptions, and provide alternate responses to maintain application reliability.

We'll cover the following...
C# 14.0
using System.Threading.Tasks;
namespace Logistics;
public class ShippingCalculator
{
public async Task<string> GetRateWithFallbackAsync()
{
try
{
string liveRate = await GetLiveShippingRateAsync().WaitAsync(TimeSpan.FromSeconds(2));
return liveRate;
}
catch (TimeoutException)
{
return "$10.00";
}
}
private async Task<string> GetLiveShippingRateAsync()
{
Random rnd = new Random();
int delay = rnd.Next(1000, 4000);
await Task.Delay(delay);
return "$15.50";
}
}
...