Fredrik
Fredrik

Reputation:

Block while waiting for event

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

Upvotes: 1

Views: 2637

Answers (1)

Jeff Yates
Jeff Yates

Reputation: 62367

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.

Upvotes: 2

Related Questions