.NET threading: how to wait for another thread to complete some task

Suppose I have a void SomeMethod (Action callback) method This method does some work on a background thread and then calls a callback. The question is how to block the current thread before calling the callback?

There is an example

bool finished = false;
SomeMethod(delegate{
 finished = true;
});
while(!finished)
  Thread.Sleep();

      

But I'm sure there must be a better way

+2


a source to share


2 answers


You can use AutoResetEvent to signal the end of a thread.

Check out this piece of code:



    AutoResetEvent terminateEvent = new AutoResetEvent(false);
    bool finished = false;
    SomeMethod(delegate
    {
        terminateEvent.Set();
    });
    terminateEvent.WaitOne();

      

+3


a source


Check Thread.Join()

will work



An example of this

+1


a source







All Articles