Aşağıdaki test kodu vardır: Ben herhangi bir istisna atmayın iplik yöntemlerindeTaskCanceledException neden oluşuyor?
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);
}
ama görevleri başlatır dış kod try-catch
bloğunda TaskCanceledException
olsun. Bu neden olur ve bu durumda token.ThrowIfCancellationRequested();
'un amacı nedir? Konu yönteminde yalnızca token.ThrowIfCancellationRequested();
numaralı telefonu çağırırsam istisnanın atılması gerektiğine inanıyorum.
Bu, VS2017 .NET Framework 4.6.2'de bir istisna oluşturmaz. –