问题
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);
}
}
The output is:
0
1
2
3
4
CancelCallback1 was called
According to http://msdn.microsoft.com/en-us/library/dd321703.aspx I expected to get AggregateException, it looks like that throwOnFirstException parameter doesn't make any sense here. What's wrong with my code.
回答1:
You need to use the Task<> class to get an AggregateException. It is a substitute for ThreadPool.QueueUserWorkItem().
回答2:
The problem is with lack of strong debugging experience in Visual Studio. My VS debugger settings were set to stop at first exception occurence.
FYI CancellationTokenSource.Cancel(false) works fine with ThreadPool as well as with Tasks.
来源:https://stackoverflow.com/questions/5299903/cancellationtokensource-cancelfalse