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.
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.
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.)
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.
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.
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.
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:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With