locked
Safe cancellation of Thread RRS feed

  • Question

  • User1904516115 posted

    What are the different ways of safe cancellation of Thread?

    Saturday, February 10, 2018 8:12 PM

Answers

  • User-166373564 posted

    Hi,

    There are basically 4 broad mechanisms for doing this.

    - Poll a stopping flag
    - Use the new cancellation mechanisms in the TPL
    - Use wait handles
    - Specialized scenarios
    - Interrupt the thread via Thread.Interrupt

    Ref: https://stackoverflow.com/a/3632642

    For example, use the new cancellation mechanisms in the TPL.

    Prior to the .NET Framework 4, the .NET Framework provided no built-in way to cancel a thread cooperatively after it was started.
    However, in .NET Framework 4, you can use cancellation tokens to cancel threads.

    The following example demonstrates how to do this.

    using System;
    using System.Threading;
    
    public class ServerClass
    {
       public static void StaticMethod(object obj)
       {
          CancellationToken ct = (CancellationToken)obj;
          Console.WriteLine("ServerClass.StaticMethod is running on another thread.");
    
          // Simulate work that can be canceled.
          while (!ct.IsCancellationRequested) {
             Thread.SpinWait(50000);
          }
          Console.WriteLine("The worker thread has been canceled. Press any key to exit.");
          Console.ReadKey(true);
       }
    }
    
    public class Simple
    {
       public static void Main()
       {
          // The Simple class controls access to the token source.
          CancellationTokenSource cts = new CancellationTokenSource();
    
          Console.WriteLine("Press 'C' to terminate the application...\n");
          // Allow the UI thread to capture the token source, so that it
          // can issue the cancel command.
          Thread t1 = new Thread(() => { if (Console.ReadKey(true).KeyChar.ToString().ToUpperInvariant() == "C")
                                         cts.Cancel(); } );
    
          // ServerClass sees only the token, not the token source.
          Thread t2 = new Thread(new ParameterizedThreadStart(ServerClass.StaticMethod));
          // Start the UI thread.
    
          t1.Start();
    
          // Start the worker thread and pass it the token.
          t2.Start(cts.Token);
    
          t2.Join();
          cts.Dispose();
       }
    }
    // The example displays the following output:
    //       Press 'C' to terminate the application...
    //
    //       ServerClass.StaticMethod is running on another thread.
    //       The worker thread has been canceled. Press any key to exit.
    

    Ref:

    Cancellation in Managed Threads
    https://docs.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads

    CancellationTokenSource Class
    https://msdn.microsoft.com/en-us/library/system.threading.cancellationtokensource(v=vs.110).aspx

    Regards,

    Angie

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, February 12, 2018 6:47 AM