views:

324

answers:

6

I have following problem:

I want to check (C#) if thread has finished execution, i.e. if the thread method returned. What I do now is call Thread.Join(1), but this gives 1 ms delay. Is there any way to simply check if thread finished. Inspecting Thread.ThreadState just seems too cumbersome.

+2  A: 

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.

ChrisF
Before calling Thread.Join(), you should always check that the current thread is different than the one you are joining. Otherwise you'll never return.
Daniel Rose
@Daniel - good point.
ChrisF
+1  A: 

For a thread you have the myThread.IsAlive property. It is false if the thread method returned or the thread was aborted.

Daniel Rose
A: 

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.

+1  A: 

Why not call 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.

Brian Gideon
A: 

You Can use Semaphore

Semaphore s= new Semaphore(0,1)
s.WaitOne();
//Do Code Here
// Ex Call Thread
s.Release();

I hope This Will Work

Hiyasat
Solution for finding the thread status?. Why semaphore is required here.
Mohanavel
You could use a Semaphore, but you would have to check its "fullness" using WaitOne(0) which is pretty much the same as just calling Thread.Join(0).
Brian Gideon
A: 

Why not thread.IsAlive flag. This is for to give the thread status.

Mohanavel