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

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

    There's a bit of bias in the MSFT docs about the disposable pattern. There are two reasons you should implement IDisposable:

    1. You've got fields of a type that implements IDisposable
    2. You've got a finalizer.

    Case 1 is pretty common in most code. Case 2 is pretty common in code that Microsoft writes, they were the ones that wrote the managed wrappers around the unmanaged resources, the ones that need finalization. But should be very uncommon in your code. After all, you've got all those nice .NET classes to do the dirty work for you. You just have to call their Dispose() methods.

    Only case 2 requires the disposable pattern. Microsoft needs to use it a lot. You'll just need the simple Dispose() most of the time.

提交回复
热议问题