Do I need to call Close() on a ManualResetEvent?

前端 未结 6 981
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 11:43

I\'ve been reading up on .NET Threading and was working on some code that uses a ManualResetEvent. I have found lots of code samples on the internet. However, when reading

6条回答
  •  佛祖请我去吃肉
    2020-12-10 12:35

    If you're using a ManualResetEvent with anonymous methods then it's obviously useful. But as Sam mentioned they can often be passed around into workers, and then set and closed.

    So I would say it depends on the context of how you are using it - the MSDN WaitHandle.WaitAll() code sample has a good example of what I mean.

    Here's an example based on the MSDN sample of how creating the WaitHandles with a using statement would exception:

    System.ObjectDisposedException
    "Safe handle has been closed"

    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;
        }
    }
    

提交回复
热议问题