我有以下测试代码:
void Button_Click(object sender, RoutedEventArgs e)
{
var source = new CancellationTokenSource();
var tsk1 = new Task(() => Thread1(source.Token), source.Token);
var tsk2 = new Task(() => Thread2(source.Token), source.Token);
tsk1.Start();
tsk2.Start();
source.Cancel();
try
{
Task.WaitAll(new[] {tsk1, tsk2});
}
catch (Exception ex)
{
// here exception is caught
}
}
void Thread1(CancellationToken token)
{
Thread.Sleep(2000);
// If the following line is enabled, the result is the same.
// token.ThrowIfCancellationRequested();
}
void Thread2(CancellationToken token)
{
Thread.Sleep(3000);
}
在线程方法中,我没有抛出任何异常,但我进入TaskCanceledException
了try-catch
启动任务的外部代码块。为什么会发生这种情况以及token.ThrowIfCancellationRequested();
在这种情况下的目的是什么。token.ThrowIfCancellationRequested();
我相信只有在调用线程方法时才应该抛出异常。