Back to Azure Sdk For

AZC0020: Propagate CancellationToken to RequestContext

sdk/tools/Azure.SdkAnalyzers/docs/AZC0020.md

2019-05-16T16-522.3 KB
Original Source

AZC0020: Propagate CancellationToken to RequestContext

Cause

A method that accepts a CancellationToken parameter calls an Azure SDK API with a RequestContext parameter, but does not propagate the cancellation token to the RequestContext.

Description

In Azure SDK for .NET, many protocol-layer APIs accept a RequestContext parameter instead of a direct CancellationToken. Since RequestContext contains a CancellationToken property, callers must propagate any incoming token into the RequestContext passed to the SDK to ensure proper cancellation support.

Missing cancellation propagation can lead to:

  • Hung requests
  • Poor responsiveness under shutdown or timeout conditions
  • Inconsistent cancellation behavior across SDK calls

How to fix violations

Set the CancellationToken property on the RequestContext object to the incoming cancellation token:

csharp
public async Task UpdateAsync(CancellationToken cancellationToken)
{
    await client.UpdateAsync(
        content,
        new RequestContext
        {
            CancellationToken = cancellationToken
        });
}

When to suppress warnings

Do not suppress warnings from this rule. Proper cancellation token propagation is critical for responsive applications and services.

Example of a violation

csharp
public async Task UpdateAsync(CancellationToken cancellationToken)
{
    // ❌ CancellationToken is accepted but not propagated
    await client.UpdateAsync(
        content,
        new RequestContext()); // cancellationToken is dropped
}

Example of how to fix

csharp
public async Task UpdateAsync(CancellationToken cancellationToken)
{
    // ✅ CancellationToken is properly propagated
    await client.UpdateAsync(
        content,
        new RequestContext
        {
            CancellationToken = cancellationToken
        });
}

Notes

  • This analyzer only reports diagnostics when calling Azure SDK APIs (methods in the Azure namespace)
  • The analyzer does not report diagnostics when a RequestContext is passed from a parameter or local variable, as it cannot determine if the token was already set
  • The analyzer works with lambda expressions and anonymous functions
  • Setting CancellationToken to CancellationToken.None or default when a cancellation token parameter is available will still trigger a warning