我有以下的測試代碼:爲什麼發生TaskCanceledException?
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);
}
在線程方法我不拋出任何異常,但我在開始的任務外碼的try-catch
塊得到TaskCanceledException
。爲什麼發生這種情況,在這種情況下token.ThrowIfCancellationRequested();
的目的是什麼。我相信只有在線程方法中調用token.ThrowIfCancellationRequested();
時纔會拋出異常。
這不會在VS2017 .NET Framework 4.6.2中引發異常。 – 2017-10-25 21:36:24