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

后端 未结 8 988
故里飘歌
故里飘歌 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:08

    One thing that it gives you is the ability to do work in Dispose() unrelated to finalization, and still clean up unmanaged resources.

    Doing anything to a managed object other than 'yourself' in a finalizer is extremely... unpredictable. Most of this is due to the fact that your finalizers will be called in stage 2 shutdown of your AppDomain in a non-deterministic manner - so when your finalizer is called, it is extremely likely that objects that you still have references to have already been finalized.

    Dispatching both the Dispose and finalizer calls to the same method allows you to share your shutdown code, while the boolean parameter allows you to skip the managed cleanup if you have any.

    Also, the virtual-ness of the method provides an easy way for inheritors to add their own cleanup code, with less of a risk of inadvertently not calling yours.

提交回复
热议问题