I have this code in my WPF Application:
this.Closing += WindowOnClosing;
CancellationTokenSource cts = new CancellationTokenSource();
private void func()
{
Task task = new Task.Factory.Start(() =>
{
// long running code...
}), cts.Token);
await task;
}
private void WindowOnClosing(CancelEventArgs e)
{
cts.Cancel();
}
But whenI close the window, the task remains in running state.
First, you should not use StartNew
in this situation; use Task.Run
instead. As I explain on my blog, StartNew
is dangerous. (I'm assuming your actual code is using StartNew
, since new Task.Factory.Start
doesn't make any sense).
Second, in my blog post on Delegate Tasks, I explain how the CancellationToken
parameter of both StartNew
and Run
is misleading.
Specifically, the CancellationToken
only cancels the scheduling of the delegate; it won't cancel the delegate itself. You have to respond to the cancellation in your own code:
private void func()
{
var token = cts.Token;
Task task = Task.Run(() =>
{
...
token.ThrowIfCancellationRequested(); // Occasionally do this.
...
});
await task;
}