.NET packaging of a call / callback pair will appear synchronously

I have a third-party COM object that I am calling that uses an event callback to signal that it has completed its task.

obj.Start();  

then after a while he will raise an event to say that it is done.

void OperationFinished()

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

eg.

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

and in the event handler:

void OperationFinished()
{
    m_autoReset.Set();
}

but it seems that both Set () and WaitOne () are in the same thread, so it gets stuck. Is there an easy way to handle this?

+3
source share
1 answer

Here quickly thought over my head. A bit detailed, but don't understand why this would not 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;
    }
}
+2

Source: https://habr.com/ru/post/1729852/


All Articles