简体   繁体   中英

.NET Threading : How to wait for other thread to finish some task

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

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();

Check for Thread.Join() will work

Example of this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM