Should we use CancellationToken with MVC/Web API controllers?

C#asp.net Mvcasp.net Web-ApiAsync AwaitCancellation Token

C# Problem Overview


There are different examples for async controllers. Some of them use CancellationToken in method definition:

public async Task<ActionResult> ShowItem(int id, CancellationToken cancellationToken)
{
    await Database.GetItem(id, cancellationToken);
    ...

But other examples and even the default ASP.NET projects for VS2013 don't use CancellationToken at all and work without it:

public async Task<ActionResult> ShowItem(int id)
{
    await Database.GetItem(id);
    ...

It's not clear, if we should use CancellationToken in controllers or not (and why).

C# Solutions


Solution 1 - C#

You should use it. Right now it only applies if you have an AsyncTimeout, but it's likely that a future MVC/WebAPI version will interpret the token as "either timeout or the client disconnected".

Solution 2 - C#

You could use this

public async Task<ActionResult> MyReallySlowReport(CancellationToken cancellationToken)
{
    CancellationToken disconnectedToken = Response.ClientDisconnectedToken;
    using (var source = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, disconnectedToken))
    {
        IEnumerable<ReportItem> items;
        using (ApplicationDbContext context = new ApplicationDbContext())
        {
            items = await context.ReportItems.ToArrayAsync(source.Token);
        }
        return View(items);
    }
}

taken from here.

Solution 3 - C#

Users can cancel requests to your web app at any point, by hitting the stop or reload button on your browser. Typically, your app will continue to generate a response anyway, even though Kestrel won't send it to the user. If you have a long running action method, then you may want to detect when a request is cancelled, and stop execution.

You can do this by injecting a CancellationToken into your action method, which will be automatically bound to the HttpContext.RequestAborted token for the request. You can check this token for cancellation as usual, and pass it to any asynchronous methods that support it. If the request is cancelled, an OperationCanceledException or TaskCanceledException will be thrown.

Below link explains this scenario in detail.

https://andrewlock.net/using-cancellationtokens-in-asp-net-core-mvc-controllers/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1224129View Question on Stackoverflow
Solution 1 - C#Stephen ClearyView Answer on Stackoverflow
Solution 2 - C#Ram YView Answer on Stackoverflow
Solution 3 - C#NidhinSPradeepView Answer on Stackoverflow