나는 다음과 같은 테스트 코드가 : 나는 예외를 포기하지 않는 스레드 방법에서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();
을 호출하면 예외가 throw되어야한다고 생각합니다.
이 예외는 VS2017 .NET Framework 4.6.2에서 예외를 throw하지 않습니다. –