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.
You can also try this aspect on try.metalama.net.
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.
Install the NuGet package: dotnet add package Metalama.Open.AutoCancellationToken.
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.