开发者

thread suicide question

开发者 https://www.devze.com 2023-01-25 12:37 出处:网络
I want开发者_StackOverflow中文版 to kill a thread when something very bad happen. What\'s your suggestion to do thread suicide?You should never actually \"kill\" a thread. From your main program, you

I want开发者_StackOverflow中文版 to kill a thread when something very bad happen. What's your suggestion to do thread suicide?


You should never actually "kill" a thread. From your main program, you can abort it using the Thread.Abort method, but this is not recommended, and it is completely unnecessary.

Your thread should be nothing more than a method executing a long loop. If something "really bad" happens, simply return from this method and thread will end.

This would be enough for such a loop:

private void MyThreadLoop()
{
   try 
   {
        while (someCondition)
        {
            // do a lengthy operation
        }
   }
   catch (Exception ex) 
   {
        Log.Error("Something bad happened: ", ex);
   }
}

public void Start() 
{  
    Thread t = new Thread(MyThreadLoop); 
    t.Start()
}

On the other hand, if you need your main program to kill the thread (but this is not a "suicide" as you named it), then you should signal the thread that you want it to end, and not abort it without knowing what is going on in the background.


There's no need to completely kill a thread, all you need to do is have it stop working on the current task.


Inside of thread, its enough to return from its function. Outside of thread, there is method Thread.Abort().


You could try something like this. The thread runs until it receives a signal from "outside" and then exists.

private static void Main(string[] args)
{
    var shouldExit = new AutoResetEvent(false);

    ThreadPool.QueueUserWorkItem(
    delegate
    {
        while (true)
        {
            Console.WriteLine("Running...");

            if (shouldExit.WaitOne(0)) break;
        }

        Console.WriteLine("Done.");
    });

    // wait a bit
    Thread.Sleep(1000);      
    shouldExit.Set();

    Console.ReadLine();
}
0

精彩评论

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