2 回答

TA貢獻(xiàn)2065條經(jīng)驗(yàn) 獲得超14個(gè)贊
要取消 IO 綁定(即運(yùn)行時(shí)間較長(zhǎng)的任務(wù)),您可以執(zhí)行以下代碼,這些代碼是我從 C# with CLR 書中獲得的。
設(shè)計(jì)任務(wù)的擴(kuò)展方法如下。
private static async Task<TResult> WithCancellation<TResult>(this Task<TResult> originalTask,
CancellationToken ct) {
// Create a Task that completes when the CancellationToken is canceled
var cancelTask = new TaskCompletionSource<Void>();
// When the CancellationToken is canceled, complete the Task
using (ct.Register(
t => ((TaskCompletionSource<Void>)t).TrySetResult(new Void()), cancelTask)) {
// Create a Task that completes when either the original or
// CancellationToken Task completes
Task any = await Task.WhenAny(originalTask, cancelTask.Task);
// If any Task completes due to CancellationToken, throw OperationCanceledException
if (any == cancelTask.Task) ct.ThrowIfCancellationRequested();
}
// await original task (synchronously); if it failed, awaiting it
// throws 1st inner exception instead of AggregateException
return await originalTask;
}
如下面的示例代碼所示,您可以使用上面設(shè)計(jì)的擴(kuò)展方法來取消它。
public static async Task Go() {
// Create a CancellationTokenSource that cancels itself after # milliseconds
var cts = new CancellationTokenSource(5000); // To cancel sooner, call cts.Cancel()
var ct = cts.Token;
try {
// I used Task.Delay for testing; replace this with another method that returns a Task
await Task.Delay(10000).WithCancellation(ct);
Console.WriteLine("Task completed");
}
catch (OperationCanceledException) {
Console.WriteLine("Task cancelled");
}
}
在此示例中,取消是根據(jù)給定時(shí)間完成的,但您可以通過調(diào)用 cancel 方法來調(diào)用取消。

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超6個(gè)贊
該問題是 IISExpress 中的錯(cuò)誤,
我切換到 Kestrel,現(xiàn)在一切都按預(yù)期進(jìn)行。
- 2 回答
- 0 關(guān)注
- 212 瀏覽
添加回答
舉報(bào)