Async, Await & Cancellation
Design an asynchronous HTTP operation that propagates cancellation, handles failures, and avoids blocking the request thread.
Examples
Compare approaches
Baseline approach
Begin by explaining the core mechanism, stating assumptions, and walking through one concrete example.
Time: Depends on design · Space: Depends on design
public async Task<string> FetchAsync(
HttpClient client, Uri uri, CancellationToken ct)
{
return await client.GetStringAsync(uri, ct);
}Strong answer
Propagate cancellation through every async operation. Reuse managed HttpClient instances. Define timeout and retry policy at the service boundary.
Time: Discuss operation costs · Space: Discuss retained state
public async Task<string> FetchAsync(
HttpClient client, Uri uri, CancellationToken ct)
{
return await client.GetStringAsync(uri, ct);
}Common traps
- Task.Result can block; async does not automatically create a new thread.
- State assumptions and justify trade-offs rather than memorizing a single answer.