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参数在这里没有任何意义。我的代码出了什么问题。
答案 0 :(得分:3)
您需要使用任务&lt;&gt;获取AggregateException的类。它是ThreadPool.QueueUserWorkItem()的替代品。
答案 1 :(得分:1)
问题在于Visual Studio缺乏强大的调试经验。我的VS调试器设置被设置为在第一次异常发生时停止。
FYI CancellationTokenSource.Cancel(false)适用于ThreadPool和任务。