Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a thread instantly in C#?

I am using the thread.Abort method 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 (Receiver.IsAlive == true)     {         MessageBox.Show("Alive");         Receiver.Abort();     }     else     {         MessageBox.Show("Dead");         Receiver.Start();     } } 

I am using this but every time I get the Alive status, Receiver is my global thread.

like image 983
Mobin Avatar asked Aug 25 '09 09:08

Mobin


People also ask

How do you stop a thread in C?

The threads exit from the start function using the pthread_exit() function with a return value. In the main function after the threads are created, the pthread_join() functions are called to wait for the two threads to complete.

How do I kill a specific thread?

tgkill() sends the signal sig to the thread with the thread ID tid in the thread group tgid. (By contrast, kill(2) can only be used to send a signal to a process (i.e., thread group) as a whole, and the signal will be delivered to an arbitrary thread within that process.)

Does killing a thread kill a process?

When you kill process, everything that process owns, including threads is also killed. The Terminated property is irrelevant. The system just kills everything. No questions asked.

How do you exit a thread?

To end the thread, just return from that function. According to this, you can also call thread. exit() , which will throw an exception that will end the thread silently.


2 Answers

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.

like image 97
redtuna Avatar answered Sep 22 '22 17:09

redtuna


You can kill instantly doing it in that way:

private Thread _myThread = new Thread(SomeThreadMethod);  private void SomeThreadMethod() {    // do whatever you want }  [SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)] private void KillTheThread() {    _myThread.Abort(); } 

I always use it and works for me:)

like image 27
Nickon Avatar answered Sep 23 '22 17:09

Nickon