开发者

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

开发者 https://www.devze.com 2022-12-30 21:17 出处:网络
Assume I have method void SomeMethod(Action callback) This method does some work in background thread and开发者_StackOverflow社区 then invokes callback. The question is - how to block current thread

Assume I have method void SomeMethod(Action callback) This method does some work in background thread and开发者_StackOverflow社区 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

0

精彩评论

暂无评论...
验证码 换一张
取 消