none
Not able to stop a thread in c# RRS feed

  • Question

  • I have an application which contains a thread running in the background. When I try to stop the  thread using thread.Abort() it does not stops, it continues execution and return exception.

    Can you suggest any better way to stop a thread and how to use thread.stop().

    Thanks in advance

     
    Friday, October 5, 2018 6:13 AM

All replies

  • Hello,

    Replace Thread with BackgroundWorker - It support Cancel operation.

    To terminate the Thread you need to exit from thread function. Abort() didn't kick you of the function - it throw an exception which suppose to kick you out of the function, but... exception can be canceled.


    Sincerely, Highly skilled coding monkey.

    Friday, October 5, 2018 6:54 AM
  • Can you post the code you're using to abort the thread along with the code that is running at the time? Aborting a thread isn't guaranteed to happen immediately (or at all). The MSDN documentation mentions the cases where it may not behave the way you expect. In general you shouldn't be using abort as this is an abrupt termination that could potentially cause issues. Instead you should implement cancellation support. If you're using Task then it is built in but you can also implement it rather easily with a ManualResetEvent for a thread.

    Michael Taylor http://www.michaeltaylorp3.net

    Friday, October 5, 2018 3:10 PM
    Moderator
  • Hi,

    you can use CancellationToken. Here is an example:

        public static void Main()
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            Thread t = new Thread((obj) => 
            {
                CancellationToken token = (CancellationToken)obj;
                while (!token.IsCancellationRequested)
                {
                    Console.WriteLine("This thread sleeps now");
                    Thread.Sleep(5000);
                }
                Console.WriteLine("This thread is canceled");
            });
            t.Start(cts.Token);
            Console.WriteLine("Thread started");
            Thread.Sleep(2000);
            cts.Cancel();
            Console.WriteLine("Cancel requested");
            while (t.IsAlive)
            {
                Console.WriteLine("Thread still running");
                Thread.Sleep(1000);
            }
            Console.WriteLine("Thread canceled");
            Console.ReadLine();
        }


    Greetings, Chris

    Friday, October 5, 2018 7:40 PM