如果你使用的是帶匿名方法的ManualResetEvent
,那麼它顯然是有用的。但是,正如山姆所說,他們經常可以被傳播到工人身邊,然後安置並關閉。
所以我會說這取決於你如何使用它的上下文 - the MSDN WaitHandle.WaitAll()代碼示例有一個很好的例子,我的意思是。
這裏的基礎上如何與using
語句創建WaitHandles會異常的MSDN樣本的例子:
System.ObjectDisposedException
「安全把手已關閉」
const int threads = 25;
void ManualWaitHandle()
{
ManualResetEvent[] manualEvents = new ManualResetEvent[threads];
for (int i = 0; i < threads; i++)
{
using (ManualResetEvent manualResetEvent = new ManualResetEvent(false))
{
ThreadPool.QueueUserWorkItem(new WaitCallback(ManualWaitHandleThread), new FileState("filename", manualResetEvent));
manualEvents[i] = manualResetEvent;
}
}
WaitHandle.WaitAll(manualEvents);
}
void ManualWaitHandleThread(object state)
{
FileState filestate = (FileState) state;
Thread.Sleep(100);
filestate.ManualEvent.Set();
}
class FileState
{
public string Filename { get;set; }
public ManualResetEvent ManualEvent { get; set; }
public FileState(string fileName, ManualResetEvent manualEvent)
{
Filename = fileName;
ManualEvent = manualEvent;
}
}
查看該代碼時,我完全錯過了使用塊。感謝您指出。 – 2010-02-10 03:54:55