QuickApi提供执行取消的功能
vipwan opened this issue · 0 comments
vipwan commented
当QuickApi执行时间很长的情况下 提供可以撤销的操作,避免长时间等待
参考代码:
[QuickApi("cancel")]
public class CancelApi : BaseQuickApi
{
public override async ValueTask<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken = default)
{
var taskJob = Task.Run(async () =>
{
//模拟操作需要5秒的长时间业务操作
await Task.Delay(5000);
//因为taskCancel线程会在提前调用CancelAsync取消,所以这里根本不会执行!
return Results.Content("Done!");
}, CancellationToken.None);
var taskCancel = Task.Run(async () =>
{
//模拟1秒后取消
await Task.Delay(1000);
//取消任务
await CancelAsync();
}, CancellationToken.None);
Task.WaitAny([taskJob, taskCancel], cancellationToken: cancellationToken);
//因为taskCancel会在1秒后调用Cancel取消,所以会抛出TaskCanceledException,
//因此下面的代码不会执行
await Task.CompletedTask;
return Results.Content("cancel api");
}
}
取消操作会抛出如下500异常:
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.6.1",
"title": "An error occurred while processing your request.",
"status": 500,
"detail": "The operation was canceled.",
"Status": 500,
"CurrentUser": null,
"Exception": {
"message": "The operation was canceled.",
"stackTrace": " at System.Threading.CancellationToken.ThrowOperationCanceledException() ..."
},
"RequestPath": "/quick/cancel",
"Method": "GET",
"QueryString": "",
"traceId": "00-2ae27a9fd064f19351be88fead3f13a6-c52f626fe9ac486f-00"
}