如果你使用的是带匿名方法的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