Ho il seguente codice di prova:Perché si verifica 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);
}
Nei metodi di filo che non gettare eccezioni, ma ho TaskCanceledException
in try-catch
blocco del codice esterno che avvia le attività. Perché questo accade e qual è lo scopo di token.ThrowIfCancellationRequested();
in questo caso. Credo che l'eccezione dovrebbe essere generata solo se chiamo token.ThrowIfCancellationRequested();
nel metodo thread.
Questo non genera un'eccezione in VS2017 .NET Framework 4.6.2. –