locked
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()
            {
                //_token.Cancel();
                while (true)
                {
                    await System.Threading.Tasks.Task.Delay(1000);
                    System.Diagnostics.Debug.WriteLine(">>");
                }
            }

    The task will not stop in 3 seconds. Why?


    Ray_ni

    Thursday, April 12, 2012 6:35 AM

Answers

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.

    http://babaandthepigman.spaces.live.com/blog/

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


    Ray_ni

    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

    --Rob

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

    Ray_ni

    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.

    --Rob

    Thursday, April 19, 2012 10:02 PM
    Moderator