Do I need to Dispose() or Close() an EventWaitHand

2019-02-03 05:10发布

If I am using EventWaitHandle (or AutoResetEvent, ManualResetEvent) to synchronise between threads then do I need to call the Close() or Dispose() methods on that event handle when I am done with it?

EventWaitHandle inherits from WaitHandle, which implements IDisposable. And FxCop complains if I don't implement IDisposable on any class that contains an EventWaitHandle. So this suggests that I do need to call it.

However none of these MSDN usage examples call Dispose() or Close():

http://msdn.microsoft.com/en-us/library/system.threading.eventwaithandle(VS.80).aspx http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent(VS.80).aspx http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent(VS.80).aspx

Is this just an example of Microsoft ignoring their own advice?

3条回答
Ridiculous、
2楼-- · 2019-02-03 05:30

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.

查看更多
在下西门庆
3楼-- · 2019-02-03 05:45

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).

查看更多
够拽才男人
4楼-- · 2019-02-03 05:46

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

查看更多
登录 后发表回答