views:

329

answers:

1

Hi,

I have an external COM-object that connects to a server and then fire an event when the server is ready. The connect() call is thus asynchronously.

My code looks (a bit...) like

ManualResetEvent waitConnection;

//This is the event that is triggered when server is ready
public void onConnection_event(bool success)
{
    if(success)
        waitConnection.Set();
}

private string getItem(string itemName)
{
    //MYDBCom is a win32 com if that makes any difference
    MYDBCom myDBobject = new MYDBCom();
    waitConnection = new ManualResetEvent(false);
    myDBobject.connect();              //asynchron call.

    //wait until server triggers the onConnection_event
    waitConnection.WaitOne();
    //server is now ready. Get the data from the server.
    return myDBobject.getItem(itemName);
}

The problem is that the event is not triggered - it seems to be blocked while waiting in WaitOne. If I instead of using waitOne use

    while(!connected)
    {
        Sleep(100);
        DoEvents();
    }

the event is triggered.

Any ideas why WaitOne blocks? Are there any other suggestions how to wait until an event triggers?

//Fredrik

+1  A: 

Because the event's message pump is on the same thread as your WaitOne call. The thread is waiting and therefore, is not pumping around your messages.

Update

I should add that using DoEvents() is not usually an advisable solution. There are often better ways of handling the scenario such as having the event fired from a different thread outside of your current thread's message pump so that your current thread doesn't need to be running for the event handler to fire.

Jeff Yates
Thanks. Seems obvious now, but since myDBobject.connect() is on another thread or process I was not certain.But I am not certain how to do this in another thread: If I run connect() in another thread I have to wait there for connect() to finish before I signal the first thread, and then it is exactly the same problem...
An observation, where in your code do you sign up for the event?
Jeff Yates