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).
So CancellationToken can be used to terminate a request execution at the server immediately once the request is aborted or orphan.
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.
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.
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.
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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With