3

I'm not sure what's the correct way of using async actions in MV5.

I don't know which one I should use.

This:

public async Task<ActionResult> Index(CancellationToken ct) { var result = await service.GetData(ct); return View(result); } 

This:

public async Task<ActionResult> Index(CancellationTokenSource cts) { var result = await service.GetData(cts.Token); return View(result); } 

Or this:

public async Task<ActionResult> Index() { var cts = CancellationTokenSource.CreateLinkedTokenSource(Request.TimedOutToken, Response.ClientDisconnectedToken); var result = await service.GetData(cts.Token); return View(result); } 

What are the difference among them?

4
  • I don't know why you would be passing in a CancellationToken or CancellationTokenSource as a parameter in a ASP.NET MVC action. Commented Sep 26, 2014 at 2:45
  • me neither! But I've found some examples doing this and there was no "why"... Commented Sep 26, 2014 at 2:47
  • Does the second one even execute? Commented Sep 26, 2014 at 3:13
  • @StephenCleary, yes. Commented Sep 26, 2014 at 14:23

1 Answer 1

3

The first example takes a CancellationToken passed to it by MVC. The second example I believe will not work at all. The third example takes two CancellationTokens from ASP.NET and combines them.

You should use the first example, probably with an AsyncTimeoutAttribute as well. AFAIK, there is a bug with Response.ClientDisconnectedToken that prevents its use in production code.

As far as the "why" goes, it's to allow cancelling requests (e.g., if they've been in progress for too long). With synchronous methods, ASP.NET will just Thread.Abort the thread assigned to the request; with asynchronous methods, ASP.NET has to be nicer and will just set a cancellation token.

Sign up to request clarification or add additional context in comments.

6 Comments

hmm.. all the 3 works fine, I'm trying to figure out if second is the same as the third. Thanks!
Does ASP.NET Web API also provide a CancellationToken if there is a parameter of that type on the action?
@TimothyShields: Yes.
@StephenCleary: You say there is a bug regarding Response.ClientDisconnectedToken? I can't find any information about this anywhere. Do you have a source or any additional information as to why this shouldn't be used?
@DeCaf: This thread identifies it as well as another bug. The same thread notes that the other bug was fixed in .NET 4.5.1, but I don't know if the ClientDisconnectedToken bug was ever fixed. The SignalR team would probably know.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.