Mam następujący kod testowy:Dlaczego występuje wyjątek 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);
}
w metodach gwintu nie rzucać żadnych wyjątków, ale pojawia TaskCanceledException
w try-catch
bloku zewnętrznego kodu, który uruchamia zadania. Dlaczego tak się dzieje i jaki jest cel tego przypadku w przypadku token.ThrowIfCancellationRequested();
. Wierzę, że wyjątek powinien być wyrzucany tylko wtedy, gdy zadzwonię pod numer token.ThrowIfCancellationRequested();
w metodzie wątku.
Nie powoduje to wyjątku w programie VS2017 .NET Framework 4.6.2. –