2

I have a running task and need to make a feature that user can stop the running task anytime. I tried to token.Cancel(); but still didn't work.

here is my code:

var task = new Task(new Action(Method), tokenSource2.Token);
 var cToken = tokenSource2.Token;
cToken.Register(() => cancelNotification());

// code to stop the running task .. button click event

 if (tokenSource2 != null)
            {

                tokenSource2.Cancel();


            }
2
  • 3
    I believe for cancellation tokens to work, the method being called as the body of the task needs to accept a cancellation token and constantly check if it has been cancelled between each step of logic. Sep 25, 2017 at 16:03
  • 2
    Task cancellation is mutual. Cancelling the token doesn't magically abort the task, the task itself has to check if the token is cancelled and exit gracefully.
    – Equalsk
    Sep 25, 2017 at 16:05

1 Answer 1

4

I believe for cancellation tokens to work, the method being called as the body of the task needs to accept a cancellation token and constantly check if it has been cancelled between each step of logic. See here for more details.

This example is an excerpt from that document and outlines how to check the status of a cancellation token.

using System;
using System.Threading;

public class Example
{
   public static void Main()
   {
      // Create the token source.
      CancellationTokenSource cts = new CancellationTokenSource();

      // Pass the token to the cancelable operation.
      ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomeWork), cts.Token);
      Thread.Sleep(2500);

      // Request cancellation.
      cts.Cancel();
      Console.WriteLine("Cancellation set in token source...");
      Thread.Sleep(2500);
      // Cancellation should have happened, so call Dispose.
      cts.Dispose();
   }

   // Thread 2: The listener
   static void DoSomeWork(object obj)
   {
      CancellationToken token = (CancellationToken)obj;

      for (int i = 0; i < 100000; i++) {
         if (token.IsCancellationRequested)
         {
            Console.WriteLine("In iteration {0}, cancellation has been requested...",
                              i + 1);
            // Perform cleanup if necessary.
            //...
            // Terminate the operation.
            break;
         }
         // Simulate some work.
         Thread.SpinWait(500000);
      }
   }
}
// The example displays output like the following:
//       Cancellation set in token source...
//       In iteration 1430, cancellation has been requested...
1
  • 2.5 seconds is a long time to wait. Wouldn't a thread join be better?
    – dmedine
    Jun 30, 2021 at 3:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.