A Metalama weaver that automatically adds CancellationToken to your method definitions and your method calls.
Install
| Product | Versions |
|---|---|
| .NET Standard |
README
Metalama.Community.AutoCancellationToken
Automatically propagates CancellationToken parameter to async methods and method calls within them.
This is a Metalama aspect. It modifies your code during compilation by using source weaving.
Example
Your code:
[AutoCancellationToken]
class C
{
async Task MakeRequests(CancellationToken ct)
{
using var client = new HttpClient();
await MakeRequest(client);
}
private static async Task MakeRequest(HttpClient client) => await client.GetAsync("https://example.org");
}
What gets compiled:
class C
{
async Task MakeRequests(CancellationToken ct)
{
using var client = new HttpClient();
await MakeRequest(client, ct);
}
private static async Task MakeRequest(HttpClient client, CancellationToken cancellationToken = default) => await client.GetAsync("https://example.org", cancellationToken);
}
Notice that CancellationToken parameter was added to the declaration of MakeRequest and that CancellationToken
argument was added to the calls of MakeRequest and HttpClient.GetAsync.
Installation
Install the NuGet package: dotnet add package Metalama.Community.AutoCancellationToken.
How to use
Add [AutoCancellationToken] to the types where you want it to apply.
By annotating a type with [AutoCancellationToken], you add cancellation to all its async methods. Specifically:
- A
CancellationTokenparameter is added to allasyncmethods that don't have it. - A
CancelltionTokenargument is added to calls withinasyncmethods where:CancellationTokencan be added as a last argument and the added argument corresponds to aCancellationTokenparameter (e.g. it's not aparams object[]parameter or a generic parameter). The added argument can result in calling a different overload of the method, or specifying a value for an optional parameter.- The call is not in a
staticlocal function. - The containing method doesn't have two or more
CancellationTokenparameters, since it wouldn't be clear which one to use.
Changes from Previous Version
Adoption Assessment
A verified publisher signal is available. Assess fit from the package's supported frameworks, license and dependency graph rather than popularity alone.
Related Guides & Workflows
Learn how to evaluate, integrate, or audit this package in your .NET project.