Search code examples
c#wpftask

Task remains in running state after closing program


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.


Solution

  • 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.

    You keep using that cancellation token there. I do not think it means what you think it means.

    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;
    }