Should we use CancellationToken with MVC/Web API controllers?

≡放荡痞女 提交于 2019-12-18 12:44:52

问题


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


回答1:


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




回答2:


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.




回答3:


Users can cancel requests to your web app at any point, by hitting the stop or reload button on your browser. Typically, your app will continue to generate a response anyway, even though Kestrel won't send it to the user. If you have a long running action method, then you may want to detect when a request is cancelled, and stop execution.

You can do this by injecting a CancellationToken into your action method, which will be automatically bound to the HttpContext.RequestAborted token for the request. You can check this token for cancellation as usual, and pass it to any asynchronous methods that support it. If the request is cancelled, an OperationCanceledException or TaskCanceledException will be thrown.

Below link explains this scenario in detail.

https://andrewlock.net/using-cancellationtokens-in-asp-net-core-mvc-controllers/



来源:https://stackoverflow.com/questions/19010856/should-we-use-cancellationtoken-with-mvc-web-api-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!