views:

87

answers:

2

Assume I have method void SomeMethod(Action callback) This method does some work in background thread and then invokes callback. The question is - how to block current thread until callback is called ?

There is an example

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

But I'm sure there should be better way

+1  A: 

Check for Thread.Join() will work

Example of this

Pranay Rana
The problem with Thread.Join is that other thread is not finished when it calls callback.
Alex Ilyin
+3  A: 

You can use AutoResetEvent to signal when your thread is finished.

Check this code snippet:

    AutoResetEvent terminateEvent = new AutoResetEvent(false);
    bool finished = false;
    SomeMethod(delegate
    {
        terminateEvent.Set();
    });
    terminateEvent.WaitOne();
Thanks, it works indeed. Does it work faster than thread sleep ?
Alex Ilyin
A spin-lock (constantly checking a flag in a while loop, possibly with a `Thread.Sleep`) is likely faster when the blocked time is very small, otherwise, `AutoResetEvent` is the way to go.
Chris Schmich