Skip to content

A small library to handle injection of cancellation token. Cancellation token are a way to cancel asynchronous call.

License

Notifications You must be signed in to change notification settings

Sulexa/Sulexa.CancellationTokenInjection

Repository files navigation

Sulexa.CancellationTokenInjection CI Nuget codecov

A small library to handle injection of cancellation token. Cancellation token are a way to stop asynchronous call.

Usage

In your startup.cs add services.AddHttpContextCancellationTokenInjection(); in the ConfigureServices method:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextCancellationTokenInjection();
}

Then you can inject CancellationTokenBase in your classes:

private readonly HttpContextCancellationToken _httpContextCancellationToken; 

public MyClass(HttpContextCancellationToken httpContextCancellationToken)
{
    this._httpContextCancellationToken = httpContextCancellationToken;
}

Example

In the following case we have an api which wait 10s before returning a result.

[HttpGet("TestCancellationAsync")]
public async Task<ActionResult<string>> TestCancellationAsync()
{
    await Task.Delay(10000);
    return Ok("Finished without cancellation");
}

If i were to call the api and cancel the call (leave the webpage, cancel the httpRequest...)
The server would continue waiting until the end and wait the 10s.

But if i choose to use my cancellation token

private readonly HttpContextCancellationToken _httpContextCancellationToken;

public CancellationTokenTestController(HttpContextCancellationToken httpContextCancellationToken)
{
    this._httpContextCancellationToken = httpContextCancellationToken;
}

[HttpGet("TestCancellationAsync")]
public async Task<ActionResult<string>> TestCancellationAsync()
{
    await Task.Delay(10000, _httpContextCancellationToken);
    return Ok("Finished without cancellation");
}

If i were to call the api and cancel the call, the Delay will stop immediately throwing an exception.

If you use entity framework core for exemple you can use cancellation token on database call (ToList(cancellationTokenBase)). It could be a great improvement on search api which are sometime called before the previous is finished.

About

A small library to handle injection of cancellation token. Cancellation token are a way to cancel asynchronous call.

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Languages