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

前端 未结 6 851
伪装坚强ぢ
伪装坚强ぢ 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:26

    You'll notice the code

     using (var mre = new ManualResetEvent(false))
     {
        // Process the left child asynchronously
        ThreadPool.QueueUserWorkItem(delegate
        {
            Process(tree.Left, action);
            mre.Set();
        });
    
        // Process current node and right child synchronously
        action(tree.Data);
        Process(tree.Right, action);
    
        // Wait for the left child
        mre.WaitOne();
    }
    

    uses the 'using' keyword. This automatically calls the dispose method when finished even if the code throws an exception.

    0 讨论(0)
  • 2020-12-10 12:29

    The Close is handled inside ManualResetEvent's Dispose, and that's called by the 'using' statement.

    http://msdn.microsoft.com/en-us/library/yh598w02%28VS.100%29.aspx

    0 讨论(0)
  • 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;
        }
    }
    
    0 讨论(0)
  • 2020-12-10 12:41

    I've used ManualResetEvent a lot and don't think I've ever used it inside a single method--it's always an instance field of a class. Therefore using() often does not apply.

    If you have a class instance field that is an instance of ManualResetEvent, make your class implement IDisposable and in your Dispose() method call ManualResetEvent.Close(). Then in all usages of your class, you need to use using() or make the containing class implement IDisposable and repeat, and repeat...

    0 讨论(0)
  • 2020-12-10 12:43

    In general, if an object implements IDisposable it is doing so for a reason and you should call Dispose (or Close, as the case may be). In the example you site, the ManualResetEvent is wrapped inside a using statement, which will "automatically" handle calling Dispose. In this case, Close is synonymous with Dispose (which is true in most IDisposable implementations that provide a Close method).

    The code from the example:

    using (var mre = new ManualResetEvent(false))
    {
       ...
    }
    

    expands to

    var mre = new ManualResetEvent(false);
    try
    {
       ...
    }
    finally
    {
       ((IDispoable)mre).Dispose();
    }
    
    0 讨论(0)
  • 2020-12-10 12:44

    I was recently forwarded an excerpt from C# 4.0 in a Nutshell: The Definitive Reference By Joseph Albahari, Ben Albahari. On page 834, in Chapter 21: Threading there is a section talking about this.

    Disposing Wait Handles

    Once you’ve finished with a wait handle, you can call its Close method to release the operating system resource. Alternatively, you can simply drop all references to the wait handle and allow the garbage collector to do the job for you sometime later (wait handles implement the disposal pattern whereby the finalizer calls Close). This is one of the few scenarios where relying on this backup is (arguably) acceptable, because wait handles have a light OS burden (asynchronous delegates rely on exactly this mechanism to release their IAsyncResult’s wait handle).

    Wait handles are released automatically when an application domain unloads.

    0 讨论(0)
提交回复
热议问题