Thread.Join vs Thread.State - c#

Thread.Join returns us if the thread has completed. The same we can determine using ThreadState. Then what is the difference between Thread.Join() and Thread.ThreadState?
Can we use them interchangeably?

The difference between Join and looking at ThreadState manually is that Join is a blocking operation. The function won't return until the timeout is reached or the target Thread completes. Checking the ThreadState is more of a peeking operation.

Thread.join WAITS for the thread to complete. ThreadState just gives you a snapshot of the thread and returns without waiting. There's also a variant of Thread.join that takes a time to wait. ThreadState and Join are extremely different and I don't think both can be used interchangeably.
Try doing a test where you do both calls on a thread that has an infinite loop.

When you call Thread.Join() it blocks the calling thread until the thread that has Join method is completed. If it is aborted, or successfully completed, Join() that follows will not block the calling thread. This allows you to have 10 worker threads and one main thread which operation must be run after all 10 threads completed. So you can call Join() on the first thread. That call will block the main thread until first working thread completes. After that you can call Join() on second thread, and so on until you get to thread #10. When you call Join() on it, and main thread gets resumed, you can be sure that all 10 threads completed and main thread can resume its operation.
For example:
Thread workers[] = new Thread[10];
//*** create and start threads ***
foreach(Thread worker in workers)
{
worker.Join();
}
//All threads are completed, now this operation can continue...
On the other hand, Thread.ThreadState only returns the thread status (Aborted, Running, ...) without affecting the calling thread's state (not as Join which puts the calling thread in WaitSleepJoin state). So this is for use only if you want to check whats happening with thread so you can take a certain action, or you want to implement your own Join mechanism, and so on...

Thread.Join will block the calling thread

Related

does monitor.wait signals the other threads

I am developing an app for windows phone 7.Now I have 2 threads.
thread 1
lock(somelock)
{
//does some work
Monitor.Wait();
//Does some work
}
thread 2
lock(somelock)
{
//does some work
Monitor.Signal();
//does some work;
}
Now I want to know whether Monitor.wait() signals the other thread.
A thread that fails to get a lock is held in the ready queue. If the thread with the lock calls Wait, then it yields the lock and any threads in the ready-queue are eligible to be activated, obtaining the lock. So in a way they are activated, but they aren't "pulsed", if that is what you mean by signalled.
By contrast, the thread that voluntarily called Wait is in a separate queue; it doesn't become activated just by a thread yielding the lock; the only way that thread gets back into the ready queue is if either a thread with the lock calls Pulse/PulseAll, or the timeout occurs. Note that Pulse/PulseAll do not yield the lock - they just more a thread/threads from the sleeping queue to the ready-queue. The lock in the second example is only yielded when leaving the lock statement. As a consequence of this, note that the "does some work" after the Pulse (Signal in your example) is still done while holding an exclusive lock (in effect, you might as well move the Pulse to the end of the lock statement).
No, but Monitor.Pulse() does. Use Monitor.Pulse() when you want to signal that the state may have changed for a Monitor.Wait() condition.
http://www.albahari.com/threading/part4.aspx#_Signaling_with_Wait_and_Pulse

how to identify if a thread has been aborted or completed

under both aborted and completed situations, ThreadState will be Stopped.
How to differentiate between them?
Your original assertion is not correct. Consider:
public static void TestThreadAbort()
{
var t = new Thread(() => Thread.Sleep(50000));
t.Start();
t.Abort();
Thread.Sleep(50);
// Prints "Aborted"
Console.WriteLine(t.ThreadState);
}
Note how the ThreadState enum is declared:
[FlagsAttribute]
public enum ThreadState { ... }
...Sinc it is a [Flag] this means a thread can be in multiple states.
MSDN, ThreadState Enumeration (emphasis added by me):
ThreadState defines a set of all possible execution states for
threads. Once a thread is created, it is in at least one of the states
until it terminates. Threads created within the common language
runtime are initially in the Unstarted state, while external threads
that come into the runtime are already in the Running state. An
Unstarted thread is transitioned into the Running state by calling
Start. Not all combinations of ThreadState values are valid; for
example, a thread cannot be in both the Aborted and Unstarted states.
...and then goes on to say:
A thread can be in more than one state at a given time. For example,
if a thread is blocked on a call to Wait, and another thread calls
Abort on the blocked thread, the blocked thread will be in both the
WaitSleepJoin and the AbortRequested states at the same time. In this
case, as soon as the thread returns from the call to Wait or is
interrupted, it will receive the ThreadAbortException to begin
aborting.
The Thread.ThreadState property of a thread provides the current state
of a thread. Applications must use a bitmask to determine whether a
thread is running. Since the value for Running is zero (0), test
whether a thread is running by using C# code such as
(myThread.ThreadState & (ThreadState.Stopped | ThreadState.Unstarted)) == 0
When a thread is aborted . You get ThreadAbortException on your thread.
This can help you in differentiating.
The only way I can think of is to set a "completed" flag as the last action in your thread. If that flag isn't set, you can assume it was aborted. As #Chris Shain points out below, you have to be careful where you put it, though, since in the case of a thread abort, you'll get a ThreadAbortException in your thread, so if you put it in the finally clause, it will get set even in the case of a thread abort.

Situation: seperated thread timer invoke UIThread and lock because a Form timer lock object

The situation is as follows: a thread timer (from System.Threading.Timer) runs in an interval and use a object to lock and do something. An UI timer (System.Windows.Forms.Timer) do also thinks on the form by interval and using the same object. So he locks this object also.
Sometimes the thread timer will do invoke the UIThread as follow:
lock (_lockobj)
{
form.Invoke(new MethodInvoker(delegate
{ // Do somethings on form }));
}
The problem is that this call will 'sleep' because the same lock on '_lockobj' is happen by the Form timer (which sleep also). So a deadlock is happen (this is what it is?).
I think it is clearly for me what is happening here but how to solve this. Or is this a design failure? Or maybe there are functions available that help me with this?
Question is: is it maybe possible that a not-UIThread invoking the form when the UIThread is sleeping?
Thanks.
This is clearly a deadlock. You must not call into other thread while holding a lock.
Explanation:
Imagine that the timer thread gets the lock, and is going to call to the UI thread. At the very same moment, the UI thread is trying to obtain the lock, and now waits for it to be released. So return to the first thread: the call into the UI thread cannot finish, because the UI thread is waiting. Deadlock.
My suggestion would be: get rid of all locking, and marshal all the operations into the UI thread. This way your calls are obviously serial (all of them happen in the same thread!), so there's no need for locking.

How to check if Thread finished execution

I have following problem:
I want to check (C#) if a thread has finished execution, i.e. if the thread method has returned. What I do now is call Thread.Join(1), but this gives a 1 ms delay. Is there any way to simply check if a thread has finished. Inspecting Thread.ThreadState just seems too cumbersome.
Use the Thread.IsAlive flag. This is to give the thread status.
For a thread you have the myThread.IsAlive property. It is false if the thread method returned or the thread was aborted.
If you don't want to block the current thread by waiting/checking for the other running thread completion, you can
implement callback method like this.
Action onCompleted = () =>
{
//On complete action
};
var thread = new Thread(
() =>
{
try
{
// Do your work
}
finally
{
onCompleted();
}
});
thread.Start();
If you are dealing with controls that doesn't support cross-thread operation, then you have to invoke the callback method
this.Invoke(onCompleted);
You could fire an event from your thread when it finishes and subscribe to that.
Alternatively you can call Thread.Join() without any arguments:
Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping.
Thread.Join(1) will:
Blocks the calling thread until a thread terminates or the specified time elapses, while continuing to perform standard COM and SendMessage pumping.
In this case the specified time is 1 millisecond.
Use Thread.Join(TimeSpan.Zero) It will not block the caller and returns a value indicating whether the thread has completed its work. By the way, that is the standard way of testing all WaitHandle classes as well.
I use IsAlive extensively, unless I want to block the current execution (of the calling thread), in which case I just call Join() without a parameter. Now, be aware that IsAlive may return false if the target thread has not actually started execution yet for any reason.
Carlos Merighe.
It depends on how you want to use it. Using a Join is one way. Another way of doing it is let the thread notify the caller of the thread by using an event. For instance when you have your graphical user interface (GUI) thread that calls a process which runs for a while and needs to update the GUI when it finishes, you can use the event to do this. This website gives you an idea about how to work with events:
http://msdn.microsoft.com/en-us/library/aa645739%28VS.71%29.aspx
Remember that it will result in cross-threading operations and in case you want to update the GUI from another thread, you will have to use the Invoke method of the control which you want to update.
Take a look at BackgroundWorker Class, with the OnRunWorkerCompleted you can do it.

Anyway to detect if a threaded method has completed

I've got a queue, which is basically the producer/consumer queue in the albahari.com
threading book, which takes an queue item off the queue, which is an action execution block off the queue and then calls a method to execute the actionlist within the queue item.
I can kill the queue easily enough by enqueing a null actionblock and block the main thread by doing a spin/wait with a thread.sleep() until the queue count goes to zero, and all the threads fall through the while !=null loop, thereby completing, but the method executing the last actionlist may still be executing the last thread.
Question is, is their anyway to detect if that method still has a thread executing it, like maybe using a Semaphore or counter with an Interlock to count the semaphore up at the beginning of the method and count it down at the end. So if it reaches zero, them I know its not threaded.
This is the implementing a destroy method on the interface, to close it down before calling dispose.
Use the Backgroundworker which has a completed event
If you start a thread like this:
System.Threading.Thread mythread = new System.Threading.Thread();
mythread.Start();
You can check:
mythread.IsAlive()
at any point to determine its status.
Use a PostSharp attribute on the method.

Categories