views:

3939

answers:

4

i am using thread.abort command to kill the thread but it not working is there any other way of terminating the thread

private void button1_Click(object sender, EventArgs e)
    {
        if (Reciever.IsAlive == true)
        {
            MessageBox.Show("Alive");
            Reciever.Abort();
        }
        else
        {
            MessageBox.Show("Dead");
            Reciever.Start();
        }
    }

i am using this but everytime i get Alive status Reciever is my global thread

+2  A: 

thread will be killed when it finish it's work, so if you are using loops or something else you should pass variable to the thread to stop the loop after that the thread will be finished.

Wael Dalloul
but there must be a way to stop it :(
Mobin
+8  A: 

The reason it's hard to just kill a thread is because the language designers want to avoid the following problem: your thread takes a lock, and then you kill it before it can release it. Now anyone who needs that lock will get stuck.

What you have to do is use some global variable to tell the thread to stop. You have to manually, in your thread code, check that global variable and return if you see it indicates you should stop.

redtuna
I use this mechanism myself. For UI-based code, I set a global variable, and for services I check a database table. Nice and predictable.
ebpower
+2  A: 

C# Thread.Abort is NOT guaranteed to abort the thread instantaneously. It will probably work when a thread calls Abort on itself but not when a thread calls on another.

Please refer to the documentation: http://msdn.microsoft.com/en-us/library/ty8d3wta.aspx

I have faced this problem writing tools that interact with hardware - you want immediate stop but it is not guaranteed. I typically use some flags or other such logic to prevent execution of parts of code running on a thread (and which I do not want to be executed on abort - tricky).

Sesh
A: 

You should first have some agreed method of ending the thread. For example a running_ valiable that the thread can check and comply with.

Your main thread code should be wrapped in an exception block that catches both ThreadInterruptException and ThreadAbortException that will cleanly tidy up the thread on exit.

In the case of ThreadInterruptException you can check the running_ variable to see if you should continue. In the case of the ThreadAbortException you should tidy up immediately and exit the thread procedure.

The code that tries to stop the thread should do the following:

running_ = false
threadInstance_.Interrupt()
if(!threadInstance_.Join(2000)) { // or an agreed resonable time
   threadInstance_.Abort()
}
Adrian Regan