We help IT Professionals succeed at work.

Disposing any open objects in C#

dev_qasource asked
Last Modified: 2012-06-22

I was looking for a C# code solution, where i can dispose all the open objects in memory.

There is a Class A which have many objects instances running. While the function executes, many objects get closed but few don't get closed due to some exceptions.

But at the End I want all the un-closed objects to be disposed finally.

Any solution on this?

Watch Question

Top Expert 2009

objects that expose the IDispose interface should be wrapped inside a using-block. That way they will be automatically disposed and you do not need to setup the finally block (which you seem to be missing currently) yourself.

using(MyDisposableType someObj = new MyDisposableType) {
    .. do something...
    .. regardless the exceptions, the objecs will be disposed of ...


Can you please provide some example here how to use it?

        ....at this point something happens and without closing the object it moves to fun2()


        //some code here


         //Now when the control comes here, we get a conflict here.
        //some code here


Question: How is it possible that all the opened objects get closed automatically before the control goes to fun2()?
Top Expert 2009
This one is on us!
(Get your first solution completely free - no credit card required)

It is fairly common to use some sort of a collection to keep track of your objects. However, what types of objects are these that are causing problems? The original code may be useful to have, here.

The "using" statement ONLY works if that object implements the System.IDisposable interface. Of course, few objects in the .NET Framework actually do, though it is useful when they do.
Top Expert 2009

> Of course, few objects in the .NET Framework actually do,

really? I see it all around, as soon as some object uses resources that cannot be guaranteed to be removed when the object goes out of scope. File.IO objects, Streams (all kinds), Process, (generic) Enumerators, all ActiveDirectory services, all Image/Drawing objects, many DB related objects etc etc.

The using-directive is still useful when using a collection of some sort, however, obviously as long as the object-count doesn't reach zero, the object will not be destroyed.

In general, it is better not to use a pool of disposable objects if you can prevent it, unless you have a real need for keeping them around.
Top Expert 2009

oh, and forgot: Form, Control are amongst them, too ;-)

I wasn't really clear on when it is needed and when not: basically whenever your object uses unmanaged resources and the .Dispose should be called in the finally block when you'd write it yourself.

If you take your miniscule list and compare it to the entire .NET Framework, you'll change your mind.

Regardless, more often than not, problems like our "client" here is having usually arise from classes that do NOT have a set-in-stone way of disposal. When managing large groups of objects like I'm guessing (from the small amount of information I do have) our client has, calling an equivalent to dipose for each and every one can be very annoying, especially if the class was not well thought out enough release any unmanaged resources in its Destructor. Letting objects merely go out of scope is just not sufficient.
Top Expert 2009

> If you take your miniscule list and compare it to the entire .NET Framework, you'll change your mind.

lol, you're right of course, and when you do a search, you only find around 350 objects that use the IDispose interface (but that's with a default Form prj with very few references). I have no idea what that is in percentage to the total, but does that matter? The point is: IDispose should be used when an object uses unmanaged resources. When only managed resources are used, there is no problem whatsoever and IDispose is not needed, which is why the majority does not need to implement IDispose, and righteously so.

> especially if the class was not well thought out enough release any unmanaged
> resources in its Destructor. Letting objects merely go out of scope is just not sufficient.

in cases where you use ill-constructed classes, you are right of course. And if everybody obeyed to the "rules" of good software design we would by now all be out of jobs and the world would be perfect.

Don't make the wrong assumption that releasing unmanaged resources in the destructor is a good thing (and sometimes not possible), they should go in Dispose, which is what it's there for. If these ill-formed classes (if they are ill-formed, but there's little information, so we are guessing) only put cleanup code in the destructor, then that's a good reason that cleanup does not work well.
Top Expert 2009

The question was: how to dispose, which I showed. The follow up question was: give example. Which I gave. The rest of the discussion was between experts and slightly off topic.

Suggestion to accept http:#24324395 as answer and http:24325239 as assist

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.