2

I have a thread:

private void start_Click(object sender, EventArgs e) {
   //...
   Thread th = new Thread(DoWork);
   th.Start(); 
}

what's the best way to know if thread is terminated? I'm looking for an example code how do this. Thanks in advance.

The Mask
  • 17,007
  • 37
  • 111
  • 185

4 Answers4

5

thread State

http://msdn.microsoft.com/en-us/library/system.threading.threadstate.aspx

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
3

There are few simple things you can do.

You could use Thread.Join to see if the thread has ended.

var thread = new Thread(SomeMethod);
thread.Start();
while (!thread.Join(0)) // nonblocking
{
  // Do something else while the thread is still going.
}

And of course if you do not specify a timeout parameter then the calling thread will block until the worker thread ends.

You could also invoke a delegate or event at the end of entry point method.

// This delegate will get executed upon completion of the thread.
Action finished = () => { Console.WriteLine("Finished"); };

var thread = new Thread(
  () =>
  {
    try
    {
      // Do a bunch of stuff here.
    }
    finally
    {
      finished();
    }
  });
thread.Start();
Brian Gideon
  • 47,849
  • 13
  • 107
  • 150
  • 1
    Usually the callback methods will try to do a cross-thread operation like updating the UI specifying that the process is completed. If your UI controls doesn't support cross-thread operation you will get a InvalidOperationException saying the control is accessed from a thread other than the thread it was created on, which can be avoided by invoking the callback method like this `this.Invoke(finished);` – shanmuga raja Mar 23 '17 at 22:06
2

If you simply want to wait until the thread is finished you can use.

th.Join();
harlam357
  • 1,471
  • 1
  • 13
  • 26
0

Simply use Thread.join() as harlam said. chech this link for more clearness: http://msdn.microsoft.com/en-us/library/95hbf2ta.aspx

Use this method to ensure a thread has terminated. The caller will block indefinitely if the thread does not terminate. If the thread has already terminated when Join is called, the method returns immediately.

M.ElSaka
  • 1,264
  • 13
  • 20