开发者

Aborting a .NET thread

I am creating a thread A and in that thread creating a new thread B.

So how is the thread hierarchy? Thread B is child of Thread A? Or the threads are created as peers?

I want to abort the parent thread A which in turn kills/aborts its child threads.

How is th开发者_开发问答at possible in C#?


Threads should ideally never be aborted. It simply isn't safe. Consider this as a way of putting down an already sick process. Otherwise, avoid like the plague.

The more correct way of doing this is to have something that the code can periodically check, and itself decide to exit.


An example of stopping threads the polite way:

using System;
using System.Threading;

namespace Treading
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Main program starts");
            Thread firstThread = new Thread(A);
            ThreadStateMessage messageToA = new ThreadStateMessage(){YouShouldStopNow = false};
            firstThread.Start(messageToA);
            Thread.Sleep(50); //Let other threads do their thing for 0.05 seconds
            Console.WriteLine("Sending stop signal from main program!");
            messageToA.YouShouldStopNow = true;
            firstThread.Join();
            Console.WriteLine("Main program ends - press any key to exit");
            Console.Read();//
        }

        private class ThreadStateMessage
        {
            public bool YouShouldStopNow = false; //this assignment is not really needed, since default value is false
        }

        public static void A(object param)
        {
            ThreadStateMessage myMessage = (ThreadStateMessage)param;
            Console.WriteLine("Hello from A");
            ThreadStateMessage messageToB = new ThreadStateMessage();
            Thread secondThread = new Thread(B);
            secondThread.Start(messageToB);

            while (!myMessage.YouShouldStopNow)
            {
                Thread.Sleep(10);
                Console.WriteLine("A is still running");
            }

            Console.WriteLine("Sending stop signal from A!");
            messageToB.YouShouldStopNow = true;
            secondThread.Join();

            Console.WriteLine("Goodbye from A");
        }

        public static void B(object param)
        {
            ThreadStateMessage myMessage = (ThreadStateMessage)param;
            Console.WriteLine("Hello from B");
            while(!myMessage.YouShouldStopNow)
            {
                Thread.Sleep(10);
                Console.WriteLine("B is still running");
            }
            Console.WriteLine("Goodbye from B");
        }
    }
}

Using Thread.Abort(); causes an exception to be thrown if your thread is in a waiting state of any kind. This is sort of annoying to handle, since there are quite a number of ways that a thread can be waiting. As others have said, you should generally avoid doing it.


Thread.Abort will do what you want, but it is not recommended to abort thread, better choose is to think a way for finishing threads correctly by Thread synchronization mechanism


Here's yet another way to politely signal a thread to die:

Note that this fashion favors finite state automatons where the slave periodically checks for permission to live, then performs a task if allowed. Tasks are not interrupted and are 'atomic'. This works great with simple loops or with command queues. Also this makes sure the thread doesn't spin 100% cpu by giving the slave thread a rest period, set this one to 0 if you don't want any rest in your slave.

var dieEvent = new AutoResetEvent(false);
int slaveRestPeriod = 20;// let's not hog the CPU with an endless loop
var master = new Thread(() =>
                            {
                                doStuffAMasterDoes(); // long running operation
                                dieEvent.Set(); // kill the slave
                            });

var slave = new Thread(() =>
                           {
                               while (!dieEvent.WaitOne(restPeriod))
                               {
                                   doStuffASlaveDoes();
                               }
                           });

slave.Start();
master.Start();


Threads are created as peers, obtain a handle to Thread A and then call ThreadA.Abort() to forcefully end it. It's better to check a boolean in the thread and if it evaluates to false exit the thread.

public class MyClass
{
    public static Thread ThreadA;
    public static Thread ThreadB;

    private void RunThings()
    {
        ThreadA = new Thread(new ThreadStart(ThreadAWork));
        ThreadB = new Thread(new ThreadStart(ThreadBWork));

        ThreadA.Start();
        ThreadB.Start();
    }

    static void ThreadAWork()
    {
        // do some stuff

        // thread A will close now, all work is done.
    }


    static void ThreadBWork()
    {
        // do some stuff

        ThreadA.Abort(); // close thread A

        // thread B will close now, all work is done.
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜