How to wait on WaitHandle without message pumping?

允我心安 提交于 2020-02-14 03:13:26

问题


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

回答1:


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




回答2:


Apparently this was a change introduced in Microsoft Vista: CoWaitForMultipleHandles now dispatches WM_PAINT messages.

Vista bug report.

A workaround is to use Microsoft's Application Compatibility Toolkit to set the DisableNewWMPAINTDispatchInOLE flag for your application.




回答3:


If you're in a WPF app where the Dispatcher is the one running the message pumps during managed waits, the simplest way to disable the message pump during your wait is via Dispatcher.DisableProcessing:

// The Dispose() method is called at the end of the using statement. 
// Calling Dispose on the DispatcherProcessingDisabled structure,  
// which is returned from the call to DisableProcessing, will 
// re-enable Dispatcher processing. 
using (Dispatcher.CurrentDispatcher.DisableProcessing())
{
    // Do work while the dispatcher processing is disabled.
    Thread.Sleep(2000);
}


来源:https://stackoverflow.com/questions/896233/how-to-wait-on-waithandle-without-message-pumping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!