匿名メソッドを使用している場合は、ManualResetEvent
明らかに便利です。しかし、Sam が述べたように、それらは多くの場合、ワーカーに渡され、設定されて閉じられます。
だから私はそれをどのように使用しているかのコンテキストに依存すると思います.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;
}
}