This is not related to WPF. Output will be same for Console application, WPF or WinForms.
As a console application this runs as expected. That same code does not run as expected in WPF. In WPF t2 Runs to completion - the line Task finished is printed in debug.
I suspect in console application you tested with ctr <= Int32.MaxValue
that's why Finised is not printed because it runs infinitely and Finish never gets printed on console.
It hits the OperationCanceledException between 0 and 100000000 but t2 keeps on running.
Exception won't stop task t2 from executing to finish at all.
OperationCanceledException
gets thrown on main thread because you ask main thread to wait on task t2 and pass cancellation token. So, with catching this exception your main thread is no longer waiting on task t2 to complete but that doesn't mean task t2 will be stopped. It will run to its complete execution. Also, main thread is now free to continue with its further execution.
This brings me to another conclusion that you might be missing Console.ReadKey()
in Main
method. That's why your console application close once exception gets thrown (main thread is not waiting anymore on task t2). Hence, you never see Finish
to be printed on Console (assuming you run loop with ctr < Int32.MaxValue
).
If you want task t2 to be stopped you can call token.ThrowIfCancellationRequested();
which will cause task t2 to be stopped if IsCancellationRequested
is set to true for token.
for (int ctr = 0; ctr < Int32.MaxValue; ctr++)
{
token.ThrowIfCancellationRequested();
if (ctr % 100000000 == 0)
Debug.WriteLine(ctr.ToString());
}