Should we use CancellationToken with MVC/Web API controllers?

后端 未结 3 1568
轮回少年
轮回少年 2020-12-29 17:51

There are different examples for async controllers. Some of them use CancellationToken in method definition:

public async Task ShowItem(i         


        
3条回答
  •  佛祖请我去吃肉
    2020-12-29 18:47

    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/

提交回复
热议问题