Is it possible to kill WaitForSingleObject(handle, INFINITE)?

Chris Wallis picture Chris Wallis · May 17, 2011 · Viewed 7.8k times · Source

I am having problems closing an application that uses WaitForSingleObject() with an INFINITE timout.

The full picture is this. I am doing the following to allow my application to handle the device wakeup event:

Register the event with:

CeRunAppAtEvent("\\\\.\\Notifications\\NamedEvents\\WakeupEvent",
    NOTIFICATION_EVENT_WAKEUP);

Start a new thread to wait on:

Thread waitForWakeThread = new Thread(new ThreadStart(WaitForWakeup));
waitForWakeThread.Start();

Then do the following in the target method:

private void WaitForWakeup()
{
    IntPtr handle = CreateEvent(IntPtr.Zero, 0, 0, "WakeupEvent");
    while (true)
    {
        WaitForSingleObject(handle, INFINITE);
        MessageBox.Show("Wakey wakey");
    }
}

This all works fine until I try to close the application when, predictably, WaitForSingleObject continues to wait and does not allow the app to close properly. We only allow one instance of our app to run at a time and we check for this on startup. It appears to continue running until the device is soft reset.

Is there a way to kill the handle that WaitForSingleObject is waiting for, to force it to return?

Many thanks.

Answer

Scott Langham picture Scott Langham · May 17, 2011

Use WaitForMultipleObject instead, and pass 2 handles. The existing one, and one for an event called something like 'exit'. During app shutdown, SetEvent on the exit event, and the WaitForMultipleObject will return and you can get it to exit the thread gracefully.

You need to switch on the return value of WaitForMultipleObject to do the appropriate behaviour depending on which one of the handles was triggered.

Possibly, also, you can set the thread to be a background thread. This will prevent it from stopping your application from shutting down when the main thread terminates.

See:

http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx