gpt4 book ai didi

c# - CancellationTokenSource.Cancel(假)

转载 作者:行者123 更新时间:2023-11-30 21:16:15 26 4
gpt4 key购买 nike

    static void Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();

ThreadPool.QueueUserWorkItem(o => DoWork(cts.Token, 100));

Thread.Sleep(500);

try
{
cts.Token.Register(CancelCallback3);
cts.Token.Register(CancelCallback2);
cts.Token.Register(CancelCallback1);



cts.Cancel(false);
}
catch (AggregateException ex)
{
foreach (Exception curEx in ex.Data)
{
Trace.WriteLine(curEx.ToString());
}

}

Console.ReadKey();
}

private static void CancelCallback1()
{
Trace.WriteLine("CancelCallback1 was called");
throw new Exception("CancellCallback1 exception");
}


private static void CancelCallback2()
{
Trace.WriteLine("CancelCallback2 was called");
throw new Exception("CancellCallback2 exception");
}

private static void CancelCallback3()
{
Trace.WriteLine("CancelCallback3 was called");
}

private static void DoWork(CancellationToken cancellationToken, int maxLength)
{
int i = 0;
while (i < maxLength && !cancellationToken.IsCancellationRequested)
{
Trace.WriteLine(i++);
Thread.Sleep(100);
}
}

输出是:

0
1
2
3
4
CancelCallback1 was called

根据 http://msdn.microsoft.com/en-us/library/dd321703.aspx我希望得到 AggregateException,看起来 throwOnFirstException 参数在这里没有任何意义。我的代码有什么问题。

最佳答案

您需要使用 Task<> 类来获取 AggregateException。它是 ThreadPool.QueueUserWorkItem() 的替代品。

关于c# - CancellationTokenSource.Cancel(假),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5299903/

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