Search code examples
.netmultithreadingcom

How to wait on WaitHandle without message pumping?


I want to call WaitHandle.WaitOne(TimeSpan) in .NET, but I'm on the STA thread and it pumps messages while waiting. For reasons that are beyond the scope of this question, I need to wait without pumping. How can I wait for a WaitHandle to be signaled without pumping messages?

It seems in some scenarios that WaitHandle.WaitOne does not pump messages. But it does sometimes for some messages. See these links for more information on that:

  1. Managed and Unmanaged Threading in Microsoft Windows
  2. Managed blocking

Solution

  • WaitForSingleObject or WaitForMultipleObjects are non-pumping waits; use p/invoke.

    [DllImport("kernel32", SetLastError=true, ExactSpelling=true)]
    public static extern Int32 WaitForSingleObject(SafeWaitHandle handle, Int32 milliseconds);
    

    -Oisin