Difference between Abort and Interrupt in Threads in .NET - c#

What is the difference between Thraed.Abort() and Thread.Interrupt(). How can I call them in a Thread Safe Manner.It would be helpful,if simple example is provided.

First of all, neither of these are good thread synchronization constructs.
First, Thread.Abort says "I don't care what you're doing, just stop doing it, and leave everything as it is right now". It's basically the programming way of saying "Hey, beat it". If your thread is having files open, those files will be left open until garbage collection gets around to finalizing your objects.
Thread.Abort should only ever be used, and even then probably not, in the case when the app domain that the thread is running inside is being torn down, preferably only when the process is being terminated.
Secondly, Thread.Interrupt is a rather strange beast. It basically says "I don't care what you're waiting for, stop waiting for it". The strange thing here is that if the thread isn't currently waiting for anything, it's instead "I don't care what you're going to wait for next, but when you do, stop waiting for it immediately".
Both of these are signs that you're imposing your will on a thread that wasn't designed to be told such things.
To abort a thread properly, the thread should periodically check some kind of flag, be it a simple volatile Boolean variable, or an event object. If the flag says "You should now terminate", the thread should terminate itself by returning from the methods in an orderly fashion.
To properly wake a thread, a thread should, in places where it has to wait for synchronization objects, include a "please stop waiting" object that it also waits on. So basically it would for either the object it needs becomes signaled, or the "please stop waiting" object becomes signaled, determine which one that did, and do the right thing.
So instead of Thread.Abort and Thread.Interrupt, you should write your threads using normal synchronization objects, like events, mutexes, semaphores, etc.
For the same reason, Thread.Suspend and Thread.Resume should be left alone, and they have also been obsoleted in the later versions of .NET.

Unless you're calling Abort or Interrupt on the currently executing thread (as ASP.NET does to terminate a request abruptly, for example) you basically can't call them in a thread-safe manner.
Use a WaitHandle or Monitor.Wait/Pulse to wait in a wakeable way. You should only abort other threads if you're tearing down the application, basically - as otherwise you can end up in an unknown state.
See my article on graceful thread termination for an example of how to do this nicely.

Thread.Abort() raises a ThreadAbortException on the target thread. It's intent to generally to force the thread to terminate. It is not a recommended practice for stopping a thread's processing.
Thread.Interrupt() interrupts a thread that is in WaitSleepJoin state - essentially blocking on a resource like a WaitHandle. This allows the caller to unblock the thread.
Neither is really "thread-safe" - in the sense that they are specifically intended to affect the behavior of threads in a way that is hard to predict.
It's generally recommended to use synchronization objects (like WaitHandles or Semaphores) to allows threads to safely synchronize with one another.

The difference between Abort and Interrupt is that while they will both throw an exception (ThreadAbortException and ThreadInterruptException), calling Abort will rethrow the exception at the end of the catch block and will make sure to end your running thread.

Related

C# locking in one thread, calling to releasing in another thread

My scenario:
a few BackgroundWorkers to perform various functions.
one of them, and only once, will have to execute to do a special work first before continue and letting other works to do their job.
I'm using Monitor.TryEnter: do this special work when it's true (locking is successful); when it's false, will wait for the lock to be released.
Problem is that this special work is done asynchronously. I have a listener, and the CompletedSpecialWork method will be called, but the Thread is different from the Thread where Monitor.TryEnter was performed (that is, the Thread holding(locking) the object). I need a way to be able to send a message to the original Thread asking to release the object.
I tried to have a static object of SynchronizationContext, but when I do threadHoldingLock = SynchronizationContext.Current it is null (it is being called from the BackgroundWorker that was able to hold the lock).
My question is: from this CompletedSpecialWork context/thread, how can I send a request to the original thread (holding the lock) to release the lock via Monitor.Exit? I need like a way to send a Invoke to the original thread with Monitor.Exit on it.
Try using either ManualResetEvent or AutoResetEvent.
These can be used to block one thread and then (via function call from a running thread into the blocked thread) allow the block to be reset.
They are syntactic sugar on top of a Semaphore but I like the simplified interface.
Good luck!
By their very nature synchronization objects like mutexes need to be released from the same thread that acquired a lock on them. It would pretty much make any kind of synchronization a crashy hit&miss affair if this requirement didn't exist and all your threads could just randomly release all locks from all threads.
You should look at Event objects to signal simple pulses between threads.

Is there a way to WAIT for a thread to complete processing while pumping windows messages?

I was trying to use AutoResetEvent.WaitOne() on a GUI thread hoping that it would not block the GUI thread completely and allow the GUI thread to keep pumping windows messages while it waits for a signal (similar to Thread.Wait()). I learned that wasn't a correct assumption.
So am looking for a way to be on the GUI Thread and wait for a thread to finish running (similar to using AutoResetEvent.WaitOne()) but keep the message pump flowing. (Please no DoEvents())
I guess the short question is: Is there a WAIT in .NET that pumps windows messages (especially "Paint" event) while it is waiting?
The CLR has a special workaround for calling WaitOne() on an STA thread. That is illegal, a thread that supports apartment threading is not allowed to block. That's very prone to cause deadlock. The CLR will in fact start taking over the duty of pumping messages, roughly similar to MsgWaitForMultipleObjects. Very roughly.
While this works to keep the basic plumbing of a UI thread alive, like painting, this is not ever something you want to do if you can avoid it. Quirky stuff can happen, not quite unlike using Application.DoEvents(), although the CLR code does try to minimize the damage that the re-entrancy can cause.
Big secret how they do this btw, it was intentionally omitted from the SSCLI20 distribution which is otherwise a very complete copy of the CLR code. Chris Brumme blogged about it, pretty impenetrable in his usual way, but with just waving his hands and not giving away any good secrets. The code itself is quite resistant to reverse engineering, it is large. The only common signs of it is finding it back in a stack trace from a programmer that's got a very hard problem to solve.
In other words, you are invoking a code path that's highly undocumented and poorly understood. Don't do it. It is fundamentally unnecessary, you can always invoke back to the UI thread and continue with the code that you've now got after the WaitOne() call. That's safe.
I don't know of any such thing that you're asking for. AFIK (as far as i know), you'll need to start a second background task or thread which waits for the AutoResetEvent to trigger in the background thread and in your UI thread, once you launch the task or 2nd thread, exit your method so it is free to do it's job of 'message pumping' as you put it.
So in this scenario, the background thread would then need to finish your processing once its AutoResetEvent is triggered to continue the processing.

When does Thread.CurrentThread.Join() make sense?

What is the effect of calling Thread.CurrentThread.Join(), and if/when would it make sense to call it?
Was it really
CurrentThread.Join()
that you saw in real code - which I kind of doubt, unless it's some hack to prevent other threads to join on the current thread - or was it
CurrentThread.Join(someTimeout)
The latter is equivalent to
Thread.Sleep(someTimeout)
except that joining on the current thread allows message pumping to continue if you are in a GUI / COM situation.
What is the effect of calling Thread.CurrentThread.Join()
You will block the execution of the current thread, and effectively dead lock it. It will cause the current thread to block until the current thread finishes, which will never happen.
, and if/when would it make sense to call it?
It really doesn't make sense to do this. You should never call this method in this manner.
On a side note, since you're using .NET 4, I would recommend avoiding using Thread.Join in general. Using the new Task/Task<T> classes is far nicer in many ways, as you can easily attach continuations (or always call Task.Wait() if you truly need to block).
It actually make sense in world of observable. Lets say you have a queue listener in main and you want to keep main thread running forever.
Instead of doing while(true) and put your code in the loop, last line you can write this. This way current thread will also be parent thread for other threads spawned within the application.
Think of it as entry point for app.
No, CurrentThread.Join() makes no sense
This could make your program stop running, making the thread A wait for thread A for example.
If you are making a unit test that tests if timers perform well in lets say a Windows Service and you use Thread.Sleep() statements with more as 60 seconds in it you can get ContextSwitch errors because the Thread.Sleep() is blocking the message pump.
If you are replacing those Thread.Sleep() statements in your unit test with Thread.CurrentThread.Join() then those ContextSwitch error will go away. So its a non blocking solution.
You could say Thread.CurrentThread.Join() is a better Thread.Sleep().
CurrentThread.Join() can be used to put the current thread to sleep until another thread interrupts it.
For example, you may have a server where the main method sets up a pool of other threads to handle incoming requests, passes a reference to it's current thread to a shutdown-trap, and then goes to sleep until it's time for the server to shut down.
This is not a terribly common pattern but it would be wrong to say that there is no case where you'd want your current thread to sleep until interrupted.

How to terminate a thread in C#?

I wanted to try my luck in threading with C#, I know a few things about threading in C.
So I just wanted to ask if i wanted to terminate a thread, I should do it with smt.Abort()
or it will "kill itself" after the function ends?
Also, is there something like pthread_exit() in C in C#?
Thread.Abort will "kill" the thread, but this is roughly equivalent to:
Scenario: You want to turn off your computer
Solution: You strap dynamite to your computer, light it, and run.
It's FAR better to trigger an "exit condition", either via CancellationTokenSource.Cancel, setting some (safely accessed) "is running" bool, etc., and calling Thread.Join. This is more like:
Scenario: You want to turn off your computer
Solution: You click start, shut down, and wait until the computer powers down.
You don't need to terminate a thread manually once the function has ended.
If you spawn up a thread to run a method, once the method has returned the thread will be shut down automatically as it has nothing further to execute.*
You can of course, manually abort a thread by simply calling Abort(), but this is pretty much un-recommended due to potential thread state corruption due to unreliable determination of where a thread is at in its current execution state. If you need to handle the killing of threads yourself, you may be best looking into using a CancellationToken. You could also read up on the Cancellation of Managed Threads article on MSDN.
** That is, unless, you're using a ThreadPool to perform your work. You shouldn't worry about aborting these threads as they're reused across different queued tasks.
Terminating a thread externally (from outside the thread) is a bad idea; you never know what the thread was in the middle of doing when you kill it asynchronously. In C#, if your thread function returns, the thread ends.
This MSDN article How to: Create and Terminate Threads (C# Programming Guide) has some notes and some sample code that you will probably find helpful.
Thread.Abort()
Thread.Join();
Thread = null;

Best way: to implement an interrupt/cancel feature for all your threaded workers

So my question is how to implement cancel/interrupt feature into all (I mean ALL) thread workers in your application in best and most elegant way?
It's not important if it's an HttpWebRequest, IO operation or calculation. User should have an possibility to cancel every action/thread at any moment.
Use .NET 4.0 Tasks with CancellationTokens - they are the new universal cancellation system.
User should have an possibility to
cancel every action/thread at any
moment.
Threading is a practice, not a design... and believe me it has been tried as a design, but it failed miserably. The basic problem with simply canceling any action at any moment is that in a multithreaded environment it's just evil! Imagine that you have a section of code guarded by a lock and you have two threads running in parallel:
Thread 1 acquires the lock.
Thread 2 waits until the lock is released so it can acquire it.
Thread 1 is canceled while it's holding the lock and it doesn't release the lock.
DEADLOCK: Thread 2 is waiting for the lock which will never be released.
This is the simplest example and technically we can take care of this situation in the design, i.e. automatically release any locks that the thread has acquired, but instead of locks think of object states, resource utilization, client dependencies, etc. If your thread is modifying a big object and it's canceled in the middle of the modification, then the state of the object may be inconsistent, the resource which you're utilizing might get hung up, the client depending on that thread might crash... there is a slew of things which can happen and there is simply no way to design for them. In this case you make it a practice to manage the threads: you ensure a safe cancellation of your threads.
Others have already mentioned various methods for starting threads that can be canceled, but I just wanted to touch on the principles. Even in the cases where there is a way to cancel your threads, you still have to keep in mind that you're responsible for determining the safest way to cancel your thread.
It's not important if it's an HttpWebRequest, IO operation or calculation.
I hope now you understand why it's the MOST important thing! Unless you specifically know what your thread is doing, then there is no safe way to automatically cancel it.
P.S.
One thing to remember is that if you don't want hanging threads then for each one of them you can set the Thread.IsBackground flag to true and they will automatically be closed when your application exits.
Your worker threads need a way to check with your main thread to see if they should keep going. One way is to share a static volatile bool that's set by your UI and periodically checked by the worker threads.
My preference is to create your own threads that run instances of a worker class that periodically invoke a callback method provided by your main thread. This callback returns a value that tells the worker to continue, pause, or stop.
Avoid the temptation to use Thread.Abort() to kill worker threads: Manipulating a thread from a different thread.

Categories

Resources