开发者

.NET wrapping a call/callback pair to appear synchronous

开发者 https://www.devze.com 2022-12-17 20:11 出处:网络
I have a 3rd party COM object I call that uses a event callback to signal it has completed its task. obj.Start();

I have a 3rd party COM object I call that uses a event callback to signal it has completed its task.

obj.Start();  

then sometime later it will raise an event to say it is done.

void OperationFinished()

I would like to be able to do this operation synchronously and have tried to use AutoResetEvents to handle this

e.g.

obj.Start();
m_autoReset.WaitOne();

and in the event handler:

void Operation开发者_Go百科Finished()
{
    m_autoReset.Set();
}

but it seems that both the Set() and the WaitOne() are on the same thread so it gets stuck. Is there a simple way to handle this?


Here's a quick thought off the top of my head. A bit verbose, but don't see why this wouldn't do the trick.

private readonly object m_locker = new object();
private volatile bool m_complete;

. .

lock (m_locker)
{
    m_complete = false;
}

obj.Start();
while (true)
{
    bool complete

    lock (m_locker)
    {
        complete = m_complete;
    }

    if (complete)
    {
        break;
    }

    Thread.Sleep(500); // Give a half-second wait to see if we're done.  YMMV.
}

. .

void OperationFinished()
{
    lock (m_locker)
    {
        m_complete = true;
    }
}
0

精彩评论

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

关注公众号