-1

I want to kill a thread when something very bad happen. What's your suggestion to do thread suicide?

user496949
  • 83,087
  • 147
  • 309
  • 426
  • Killing a thread **is** something very bad. – Greg Hewgill Nov 16 '10 at 07:37
  • 7
    See [How to kill a thread instantly in C# ? ](http://stackoverflow.com/questions/1327102/how-to-kill-a-thread-instantly-in-c). Also, I think you mean homicide... :) – Matthew Flaschen Nov 16 '10 at 07:38
  • 2
    It's not considered suicide if you force the thread – Toad Nov 16 '10 at 07:39
  • 1
    surely it would be better to deal the "very bad thing" inside the thread with exception handling and exit gracefully? At least then you can record the stack and try to work out why the "very bad thing" happened in the first place... – Jonathan Day Nov 16 '10 at 07:48

4 Answers4

3

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.

vgru
  • 49,838
  • 16
  • 120
  • 201
0

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

Rob Fonseca-Ensor
  • 15,510
  • 44
  • 57
0

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

alxx
  • 9,897
  • 4
  • 26
  • 41
0

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();
}
gevorg
  • 4,835
  • 4
  • 35
  • 52
Gregor Slavec
  • 4,814
  • 1
  • 26
  • 24