What's the point of overriding Dispose(bool disposing) in .NET?

后端 未结 8 983
故里飘歌
故里飘歌 2021-01-30 10:38

If I write a class in C# that implements IDisposable, why isn\'t is sufficient for me to simply implement

public void Dispose(){ ... } 

to han

8条回答
  •  不思量自难忘°
    2021-01-30 11:26

    Just to expand on what others have said: it's not just that you don't need the 'complex dispose', it's that you actually don't want it, for performance reasons.

    If you go the 'complex dispose' route, and implement a finalizer, and then forget to explicitly dispose your object, your object (and anything it references) will survive an extra GC generation before it's really disposed (since it has to hang around one more time for the CLR to call the finalizer). This just causes more memory pressure that you don't need. Additionally, calling the finalizer on a whole heap of objects has a non-trivial cost.

    So avoid, unless you (or your derived types) have unmanaged resources.

    Oh, and while we're in the area: methods on your class which handle events from others must be 'safe' in the face of being invoked after your class has been disposed. Simplest is to just perform a no-op if the class is disposed. See http://blogs.msdn.com/ericlippert/archive/2009/04/29/events-and-races.aspx

提交回复
热议问题