I like threads, but I can't find any information on the Internet (maybe I just don't Know how to search for that properly) regarding what happen in the background when for example thread starvation is on the stage. How does OS handles it? Do my thread waits in the line to get it's chance to be created in the thread pool or is it killed after xy time when it can't be created? Or is it something totally else?
Another question is why should I care about thread context? By calling ConfigureAwait(false) from what I know I am not waiting for that thread context which can be translated as "I don't care about that context". From what I know by calling ConfigureAwait(false) I am taking care of deadlocks.
The last question is, when a deadlock happen, what is going on in the background? Do main thread tries to catch that context or something else?
I think deadlock is used in the wrong context here. Deadlock describes a situation where two or more threads are blocked forever, waiting for each other (e.g. by lock statement).
Thread starvation: Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress.
Do my thread waits in the line to get it's chance to be created in the thread pool or is it killed after xy time when it can't be created?
I don't really understand this question.
Your thread doesn't wait to be created. Your function creates the thread.
Another question is why should I care about thread context?
From MSDN: "A context is an ordered sequence of properties that define an environment for the objects resident inside it. Contexts get created during the activation process for objects that are configured to require certain automatic services, such as synchronization, transactions, just-in-time activation, security, and so on. Multiple objects can live inside a context."
Here a similar question :Why would I bother to use Task.ConfigureAwait(continueOnCapturedContext: false);
The last question is, when a deadlock happen, what is going on in the background?
The two threads keep running (waiting for each other) until you close the application.
Related
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;
My model of how threads work is that some ThreadManager gives each thread a turn. When it's a thread's turn, it gets to execute a few lines of code.
To pause a thread, couldn't one just have the ThreadManager (momentarily) stop allowing that thread to have a turn?
To abort a thread, couldn't the ThreadManager just never give that thread another turn?
What's the problem?
Quote from MSDN about pausing threads:
You have no way of knowing what code a
thread is executing when you suspend
it. If you suspend a thread while it
holds locks during a security
permission evaluation, other threads
in the AppDomain might be blocked. If
you suspend a thread while it is
executing a class constructor, other
threads in the AppDomain that attempt
to use that class are blocked.
Deadlocks can occur very easily.
Aborted thread can lead to unpredicted circumstances. There is a good article about this: http://www.bluebytesoftware.com/blog/2009/03/13/ManagedCodeAndAsynchronousExceptionHardening.aspx
I agree with Alex, but to elaborate further, if you need to "pause" a thread, it will probably be better to look at some sort of locking mechanism like Semaphores, Mutexes, or one of the many other ones available.
But, without knowing your code, Windows is a preemptive multitasking environment. Usually this is not needed, just let your threads run and the underlying OS and scheduler will make sure all your tasks get a fair turn.
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.
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.
Or is it okay to do something like this:
new Thread( new ThreadStart( delegate { DoSomething(); } ) ).Start();
?
I seem to recall that under such a scenario, the Thread object would be garbage collected, but the underlying OS thread would continue to run until the end of the delegate passed into it. I'm basically looking for ThreadPool functionality, but don't want the threads to be background threads (i.e. I want them to keep the app alive).
Update:
According to Jason, the CLR actually keeps an internal reference to the Thread object, while running, so it won't be garbage collected until the thread exits.
I have generally found that if I need to directly start a new thread the way you are in your example, rather than grabbing one from the thread pool, then it is a long running thread and I will need a reference to it later to kill it, monitor it, etc. For short run threads like invoking IO on a background thread, etc, I always use a thread pool thread (usually indirectly through a someDelete.BeginBlah(...) method call). When using a thread pool thread like this I prefer to NOT keep a reference around. I don't know if another programmer might inappropriately use a reference to that thread. If I don't need a reference, I don't keep it around to clutter up code.
Edit: To answer your edit about threads being garbage collected, this will not occur while the thread is running. The CLR keeps a reference to every running thread. The object representing the thread will NOT be collected.
It depends. In the situation where the user can cancel the operation of your thread, you should keep the reference so the thread can be canceled when the user want. In other situations, there may be no need to store the reference.
I have had a number of cases in production code where doing this has been appropriate. So, yes defining and starting a thread in one line without retaining a reference has it's place. I think keeping a reference "just in case" you redesign later and need it is failing the principle of creating the simplest thing that works.
And, to the second part, no it will not be GC'd while it is running; threads are root level objects from which the GCtor will chase down references. The Thread instance will only be GCd once it is no longer reachable by any running thread including the one which you start on it.
And beware leaking Thread instances which are created but never started. I believe they will hang around forever.
It might be good to ask the question "How often can this thread be started up?" Is it per-application, per-class, per-object instance, or per-method invocation? This may tell you what kind of variable (if any) to store it in.
Yes, you should, because you never know when you will have to change the code later to handle the thread in some way. That, and putting too much stuff on one line like that is just ugly.
So truthfully, you can do it your way, so the answer really comes down to code style preference.
In addition to what "m3rLinEz" has posted above, another draw back is that if any exception occurs in your thread it will be hard to even detect such cases.