取消客户端上长时间运行的操作 cancel

我使用 ASP.NET Core 和 Razor Pages 开始了我的第一个项目。根据客户端请求,将启动长时间运行的数据库操作。现在我想认识到,当用户离开网站时,可以取消数据库操作。


我已经尝试过使用cancelToken,但它永远不会被取消。


public async Task<JsonResult> OnPostReadAsync([DataSourceRequest] DataSourceRequest request, CancellationToken cancellationToken)

{

    var messages = await _logMessageService.GetLogMessagesAsync(request, cancellationToken);


    return new JsonResult(messages.ToDataSourceResult(request));

}

该函数由 Telerik Kendo UI 网格调用。你能告诉我,为什么取消令牌没有被取消,或者我还有什么其他选项来检测客户端的堕胎?


编辑1


我将令牌传递给 NpgsqlCommand 的此函数调用:


var dataReader = await command.ExecuteReaderAsync(cancellationToken);


临摹微笑
浏览 157回答 2
2回答

翻翻过去那场雪

要取消 IO 绑定(即运行时间较长的任务),您可以执行以下代码,这些代码是我从 C# with CLR 书中获得的。设计任务的扩展方法如下。private static async Task<TResult> WithCancellation<TResult>(this Task<TResult> originalTask,CancellationToken ct) {&nbsp; &nbsp;// Create a Task that completes when the CancellationToken is canceled&nbsp; &nbsp;var cancelTask = new TaskCompletionSource<Void>();&nbsp; &nbsp;// When the CancellationToken is canceled, complete the Task&nbsp; using (ct.Register(&nbsp; &nbsp; &nbsp;t => ((TaskCompletionSource<Void>)t).TrySetResult(new Void()), cancelTask)) {&nbsp; &nbsp; // Create a Task that completes when either the original or&nbsp; &nbsp; // CancellationToken Task completes&nbsp; &nbsp; Task any = await Task.WhenAny(originalTask, cancelTask.Task);&nbsp; &nbsp; // If any Task completes due to CancellationToken, throw OperationCanceledException&nbsp; &nbsp; &nbsp;if (any == cancelTask.Task) ct.ThrowIfCancellationRequested();&nbsp; }&nbsp; // await original task (synchronously); if it failed, awaiting it&nbsp; // throws 1st inner exception instead of AggregateException&nbsp;return await originalTask;}如下面的示例代码所示,您可以使用上面设计的扩展方法来取消它。public static async Task Go() {&nbsp; &nbsp;// Create a CancellationTokenSource that cancels itself after # milliseconds&nbsp; &nbsp;var cts = new CancellationTokenSource(5000); // To cancel sooner, call cts.Cancel()&nbsp; &nbsp;var ct = cts.Token;&nbsp; &nbsp;try {&nbsp; &nbsp; // I used Task.Delay for testing; replace this with another method that returns a Task&nbsp; &nbsp; &nbsp;await Task.Delay(10000).WithCancellation(ct);&nbsp; &nbsp; &nbsp;Console.WriteLine("Task completed");&nbsp; &nbsp;}&nbsp; &nbsp;catch (OperationCanceledException) {&nbsp; &nbsp; Console.WriteLine("Task cancelled");&nbsp; }}在此示例中,取消是根据给定时间完成的,但您可以通过调用 cancel 方法来调用取消。

慕尼黑的夜晚无繁华

该问题是 IISExpress 中的错误,我切换到 Kestrel,现在一切都按预期进行。
打开App,查看更多内容
随时随地看视频慕课网APP