Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

public void Dispose(){ ... }  

to handle freeing any unmanaged resources?

Is

protected virtual void Dispose(bool disposing){ ... } 

always necessary, sometimes necessary, or something else altogether?

like image 403
Mark Carpenter Avatar asked Feb 25 '09 02:02

Mark Carpenter


People also ask

What is protected override void Dispose bool disposing?

A protected override void Dispose(bool) method that overrides the base class method and performs the actual cleanup of the derived class. This method must also call the base. Dispose(bool) ( MyBase. Dispose(bool) in Visual Basic) method passing it the disposing status ( bool disposing parameter) as an argument.

Why do we need Dispose in C#?

In the context of C#, dispose is an object method invoked to execute code required for memory cleanup and release and reset unmanaged resources, such as file handles and database connections.

What does DB Dispose () do?

Dispose is for releasing "unmanaged" resources (for example, sockets, file handles, Bitmap handles, etc), and if it's being called outside a finalizer (that's what the disposing flag signifies, BTW), for disposing other IDisposable objects it holds that are no longer useful.

Why we need to implement Dispose method while we have option to implement destructor?

It is always recommended to use Dispose method to clean unmanaged resources. You should not implement the Finalize method until it is extremely necessary. At runtime C#, C++ destructors are automatically converted to Finalize method.


1 Answers

The full pattern including a finalizer, introduction of a new virtual method and "sealing" of the original dispose method is very general purpose, covering all bases.

Unless you have direct handles on unmanaged resources (which should be almost never) you don't need a finalizer.

If you seal your class (and my views on sealing classes wherever possible are probably well known by now - design for inheritance or prohibit it) there's no point in introducing a virtual method.

I can't remember the last time I implemented IDisposable in a "complicated" way vs doing it in the most obvious way, e.g.

public void Dispose() {     somethingElse.Dispose(); } 

One thing to note is that if you're going for really robust code, you should make sure that you don't try to do anything after you've been disposed, and throw ObjectDisposedException where appropriate. That's good advice for class libraries which will be used by developers all over the world, but it's a lot of work for very little gain if this is just going to be a class used within your own workspace.

like image 73
Jon Skeet Avatar answered Sep 21 '22 09:09

Jon Skeet