如果您使用的是ManualResetEvent
匿名方法,那么它显然很有用。但正如 Sam 提到的,它们通常可以传递给工人,然后设置和关闭。
所以我想说这取决于你如何使用它的上下文 - MSDN WaitHandle.WaitAll()代码示例有一个很好的例子来说明我的意思。
下面是一个基于 MSDN 示例的示例,说明如何使用using
语句创建 WaitHandles 会出现异常:
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;
}
}