मैं निम्नलिखित परीक्षण कोड है: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();
पर कॉल करता हूं।
यह वीएस2017 .NET Framework 4.6.2 में अपवाद नहीं फेंकता है। –