Reputation: 2003
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?
Upvotes: 3
Views: 1195
Reputation: 457302
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 CancellationToken
s 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.
Upvotes: 3