我们有一个.NET Framework前端,它调用一个.NET Core Web API来检索项目以展示给用户。如果用户调用了数万个项目并决定取消请求,它会继续消耗资源来获取项目,而我们知道用户不再需要检索。在.NET中,一旦呼叫到达服务,是否有一种取消呼叫的方法?
了解CancellationTokens
在一个示例控制器中
public class SlowRequestController : Controller
{
private readonly ILogger _logger;
public SlowRequestController(ILogger<SlowRequestController> logger)
{
_logger = logger;
}
[HttpGet("/slowtest")]
public async Task<string> Get()
{
_logger.LogInformation("Starting to do slow work");
// slow async action, e.g. call external api
await Task.Delay(10_000);
var message = "Finished slow delay of 10 seconds.";
_logger.LogInformation(message);
return message;
}
}
public class SlowRequestController : Controller
{
private readonly ILogger _logger;
public SlowRequestController(ILogger<SlowRequestController> logger)
{
_logger = logger;
}
[HttpGet("/slowtest")]
public async Task<string> Get(CancellationToken cancellationToken)
{
_logger.LogInformation("Starting to do slow work");
for(var i=0; i<10; i++)
{
cancellationToken.ThrowIfCancellationRequested();
// slow non-cancellable work
Thread.Sleep(1000);
}
var message = "Finished slow delay of 10 seconds.";
_logger.LogInformation(message);
return message;
}
}
您没有提到前端的外观,但您需要某种方式来从客户端请求中发出取消信号。一个例子可能是:
var xhr = $.get("/api/slowtest", function(data){
//show the data
});
//If the user navigates away from this page
xhr.abort()
这里有很好的例子:
https://andrewlock.net/using-cancellationtokens-in-asp-net-core-mvc-controllers/
还有这里: