Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we use CancellationToken with MVC/Web API controllers?

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

like image 875
user1224129 Avatar asked Sep 25 '13 16:09

user1224129


People also ask

When should I use CancellationToken?

So CancellationToken can be used to terminate a request execution at the server immediately once the request is aborted or orphan.

What is the purpose of CancellationToken?

A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource. Token property.

Can we call Web API from MVC controller?

In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller. Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below. Then give it a suitable name and click OK.

What is cancellation token in Web API?

Cancellation is a way to signal to an async task that it should stop doing whatever it happens to be doing. In . NET, this is done using a CancellationToken. An instance of a cancellation token is passed to the async task and the async task monitors the token to see if a cancellation has been requested.


2 Answers

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

like image 186
Stephen Cleary Avatar answered Oct 04 '22 13:10

Stephen Cleary


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.

like image 20
Ram Y Avatar answered Oct 04 '22 13:10

Ram Y