0

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.

ali khezri
  • 453
  • 1
  • 4
  • 18
  • http://stackoverflow.com/questions/10134310/how-to-cancel-a-task-in-await – mohsen May 28 '16 at 08:54
  • 1
    You should cancel the closing in the `WindowOnClosing` handler and set a continuation for your task that closes the window on task cancellation. – Charles Mager May 28 '16 at 09:29

2 Answers2

2

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;
}
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • That only explains why he could never expect that the task is canceled once it start running. That did not explain, why he also can't expect the canceled state when the application finishes. There has to be a wait for the task – Sir Rufo May 28 '16 at 17:00
-1

I think after Cancel task you should wait for cancellation :

task.Wait();

also here is useful :

https://msdn.microsoft.com/en-us/library/dd997396%28v=vs.110%29.aspx

  • 2
    This would accomplish nothing other than to freeze the UI of his program for an extended period of time; it would in no way actually cancel the background task. – Servy May 28 '16 at 15:58
  • Its not cancel the task , its after sending the cancel flag and just wait to response the task, because the task maybe in work and after first time see the cancel flag it stop the task, after all its in the msdn ... – Arman.Salehi May 28 '16 at 17:22
  • No, the problem with the OP's code is that he's not actually cancelling the task. It's *desirable* that he isn't synchronously waiting on it. Adding that only breaks the code *even more*. It doesn't solve the actual problem, and it's actively harmful with or without adding the actual solution. – Servy May 28 '16 at 20:39