Do I need to Dispose() or Close() an EventWaitHandle?

前端 未结 4 671
借酒劲吻你
借酒劲吻你 2020-12-28 15:35

If I am using EventWaitHandle (or AutoResetEvent, ManualResetEvent) to synchronise between threads then do I need to call the Cl

相关标签:
4条回答
  • 2020-12-28 15:57

    You need to dispose them explicitly. Close() is more appropriate for them as it does call Dispose().

    0 讨论(0)
  • 2020-12-28 16:03

    The disposable resource of an EventWaitHandle is actually a SafeHandle (wrapped in a SafeWaitHandle). SafeHandle implements a finalizer, which eventually makes sure the necessary resource is release, so it should be safe to let the garbage collector / finalizer thread handle it in this case.

    However, it is always a good idea to explicitly call Dispose() when the resource is no longer needed.

    The threading chapter in C# 3.0 in a Nutshell states

    This practice is (arguably) acceptable with wait handles because they have a light OS burden (asynchronous delegates rely on exactly this mechanism to release their IAsyncResult's wait handle).

    0 讨论(0)
  • 2020-12-28 16:13

    Close method disposes it internally.

    0 讨论(0)
  • 2020-12-28 16:17

    Class definitions from MSDN:

    public class EventWaitHandle : WaitHandle
    public abstract class WaitHandle : MarshalByRefObject, IDisposable
    

    So yes you must as WaitHandle is IDisposable. FxCop would find this as a rule violation if you didn't.

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