问题
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.
回答1:
Use the Thread.IsAlive flag. This is to give the thread status.
回答2:
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.
回答3:
For a thread you have the myThread.IsAlive
property. It is false if the thread method returned or the thread was aborted.
回答4:
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.
回答5:
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);
回答6:
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.
回答7:
Take a look at BackgroundWorker Class, with the OnRunWorkerCompleted you can do it.
回答8:
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.
来源:https://stackoverflow.com/questions/2773479/how-to-check-if-thread-finished-execution