A blocked thread can be released in one of two ways:
- Using Thread.Interrupt
- Using Thread.Abort
The lock that frees a thread must be implemented by another active thread, and the waiting thread itself is unable to do anything for its blocked state.
Interrupt Method
Calling the interrupt method on a blocked thread will force it to be released while throwing the threadinterruptedexception exception, as follows:
classProgram {Static voidMain () {Thread T=NewThread (Delegate() { Try{thread.sleep (timeout.infinite); } Catch(threadinterruptedexception) {Console.Write ("forcibly"); } Console.WriteLine ("woken!"); }); T.start (); T.interrupt (); }} output:forcibly Woken!
Interrupting a thread simply frees its current (or next) wait state and does not end the thread (unless, of course, the threadinterruptedexception exception is not handled).
If interrupt is called by an unblocked thread, the thread will continue execution until the next time it is blocked, it throws a ThreadInterruptedException exception. Use the following test to avoid this problem, but this is not a thread-safe way.
if 0 ) worker. Interrupt ();
Random thread breaks are risky because any framework or third-party method can accidentally receive interrupts on the subscribed code when it calls the stack. If this method is not designed to be interrupted (no proper handling of the finally block), there may be no useless state, or the resource is not completely released. If you know exactly where to break, it is safe to interrupt a thread, such as a signaling system.
Abort Method
Blocked threads can also be forcibly freed through the Abort method, similar to calling interrupt, except that the threadinterruptedexception exception is replaced with a ThreadAbortException exception. The exception is thrown in the catch until Thread.resetabort is called in the catch, during which the thread's ThreadState is abortrequested.
The biggest difference between Interrupt and Abort is what happens when they invoke a non-blocking thread. Interrupt continues to work until the next stop, where the abort thread is currently executing (perhaps not even in your code) throws an exception. Terminating a non-blocking thread can have serious consequences.
C # Multithreading Practice-Early release locks