gpt4 book ai didi

c# - 如何捕捉 CancellationToken.ThrowIfCancellationRequested

转载 作者:行者123 更新时间:2023-12-05 03:09:08 25 4
gpt4 key购买 nike

这段代码执行时

cancellationToken.ThrowIfCancellationRequested();

try catch block 不处理异常

    public EnumerableObservable(IEnumerable<T> enumerable)
{
this.enumerable = enumerable;
this.cancellationSource = new CancellationTokenSource();
this.cancellationToken = cancellationSource.Token;


this.workerTask = Task.Factory.StartNew(() =>
{
try
{
foreach (var value in this.enumerable)
{
//if task cancellation triggers, raise the proper exception
//to stop task execution

cancellationToken.ThrowIfCancellationRequested();

foreach (var observer in observerList)
{
observer.OnNext(value);
}
}
}
catch (AggregateException e)
{
Console.Write(e.ToString());
}
}, this.cancellationToken);

}

最佳答案

AggregateExceptions在异步操作期间可能出现大量异常时抛出。它们包含所有引发的异常,例如在链接Tasks (通过 . ContinueWith )或级联内 async/await电话。

正如@Mitch Stewart 指出的那样,要处理的正确异常类型是 OperationCancelledException在你的例子中。

关于c# - 如何捕捉 CancellationToken.ThrowIfCancellationRequested,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43769143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com