Asynchronous Actions in MVC 5

I'm not sure what is the correct way to use asynchronous actions in MV5.

I don't know which one I should be using.

It:

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

      

It:

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

      

Or that:

public async Task<ActionResult> Index()
{
    var cts = CancellationTokenSource.CreateLinkedTokenSource(Request.TimedOutToken, Response.ClientDisconnectedToken);

    var result = await service.GetData(cts.Token);
    return View(result);
}

      

What is the difference between them?

+3


source to share


1 answer


The first example takes the CancellationToken

MVC passed to it. The second example, in my opinion, will not work. The third example takes two CancellationToken

from ASP.NET and combines them.

You should use the first example, perhaps c AsyncTimeoutAttribute

. AFAIK, there is a bug with Response.ClientDisconnectedToken

that prevents it from being used in production code.



As for the "why", this allows you to cancel requests (for example, if they are too long). With synchronous methods, ASP.NET will simply be the Thread.Abort

thread assigned to the request; with async methods, ASP.NET should be nicer and just set a cancellation token.

+3


source







All Articles