2009-05-22 77 views
10

我想在.NET中調用WaitHandle.WaitOne(TimeSpan),但我在STA線程中,它在等待時泵送消息。由於超出此問題範圍的原因,我需要等待而不抽取。我如何等待WaitHandle被髮送信號而沒有信息?如何在WaitHandle上等待沒有消息抽取?

在某些情況下,WaitHandle.WaitOne似乎不會泵送消息。但它有時候會有一些消息。查看這些鏈接以獲取更多信息:

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

我知道問題已經得到解答,但是您能否給出一個說明WaitHandle.WaitOne泵送消息的配方?我真的不明白這裏發生了什麼,我很好奇。 – 2009-05-25 12:48:18

+0

wcoenen:我在我的問題中添加了一些鏈接,指出WaitOne有時會傳遞消息。 – 2009-05-25 23:01:35

回答

8

WaitForSingleObject的或WaitForMultipleObjects的都是非抽水等待;使用p/invoke。

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

-Oisin

1

如果你在一個WPF應用程序,其中的調度程序正在運行的消息一個是泵中管理的等待,你的等待過程中禁用消息泵的簡單方法是通過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); 
}