Cancel the task RRS feed

  • Question

  • With the API: CancellationTokenSource .Cancel()  cannot cancel the task as I want.

    Follow is my codes:

            private async void StartWork()
                _token = new CancellationTokenSource(3000);
                await System.Threading.Tasks.Task.Run(new Action(DoWork), _token.Token);
            private async void DoWork()
                while (true)
                    await System.Threading.Tasks.Task.Delay(1000);

    The task will not stop in 3 seconds. Why?


    Thursday, April 12, 2012 6:35 AM


All replies

  • Try passing the token to the delay task..

    await System.Threading.Tasks.Task.Delay(1000, _token.Token);
    an OperationCancelledException will be thrown after 3 secs.


    • Marked as answer by NMG1852951 Tuesday, April 17, 2012 2:25 AM
    • Unmarked as answer by NMG1852951 Tuesday, April 17, 2012 2:27 AM
    • Marked as answer by NMG1852951 Tuesday, April 17, 2012 3:09 AM
    Thursday, April 12, 2012 9:02 AM
  • Well,  this is a good way to console my problem.

    But if there is no Task.Delay in my task code, How could I do?


    Tuesday, April 17, 2012 2:26 AM
  • The cancellation token is a request for the task to cancel. In your task you'll need to look at the token to see if it IsCancellationRequested has been set. If it has been set, then cancel out of the task.

    See Cancellation in Managed Threads


    Tuesday, April 17, 2012 3:04 AM
  • Well, you means, I need to cancel the task by myself ?


    Tuesday, April 17, 2012 3:07 AM
  • Yes. Only you know when and how your task can be cancelled, so you will have to write the code to check that and cancel out.


    Thursday, April 19, 2012 10:02 PM