如何在没有消息的情况下等待WaitHandle?

时间:2009-05-22 03:21:59

标签: .net multithreading com

我想在.NET中调用WaitHandle.WaitOne(TimeSpan),但我在STA线程上,并在等待时抽取消息。由于超出此问题范围的原因,我需要等待而不抽水。如何在不抽取消息的情况下等待WaitHandle发出信号?

在某些情况下,WaitHandle.WaitOne似乎不会传递消息。但它有时会发生一些消息。有关详细信息,请参阅以下链接:

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

3 个答案:

答案 0 :(得分:8)

WaitForSingleObject或WaitForMultipleObjects是非抽空等待;使用p / invoke。

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

-Oisin

答案 1 :(得分:3)

显然这是change introduced in Microsoft VistaCoWaitForMultipleHandles现在发送WM_PAINT条消息。

Vista bug report

解决方法是使用Microsoft的应用程序兼容性工具包为您的应用程序设置DisableNewWMPAINTDispatchInOLE标志。

答案 2 :(得分:1)

如果你在一个WPF应用程序中Dispatcher是在托管等待期间运行消息泵的人,那么在等待期间禁用消息泵的最简单方法是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);
}