Should we use CancellationToken with MVC/Web API controllers?

user1224129 picture user1224129 · Sep 25, 2013 · Viewed 23.7k times · Source

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).

Answer

Stephen Cleary picture Stephen Cleary · Sep 25, 2013

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".