Solved

Disposing any open objects in C#

Posted on 2009-05-07
11
303 Views
Last Modified: 2012-06-22
Hi,

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

Question:
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?

0
Comment
Question by:dev_qasource
  • 6
  • 2
11 Comments
 
LVL 39

Expert Comment

by:abel
ID: 24324395
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 ...
}
0
 

Author Comment

by:dev_qasource
ID: 24324832
Can you please provide some example here how to use it?

namespace
{
   class
    {  
       fun1()
       {
          obj1.share();
        ....at this point something happens and without closing the object it moves to fun2()

        obj1.close();
       
        obj2.share();

        //some code here

        obj2.close();

       }
     fun2()
      {
         //Now when the control comes here, we get a conflict here.
          obj1.share();
         
        //some code here

          obj1.close();
      }
    }
}


Question: How is it possible that all the opened objects get closed automatically before the control goes to fun2()?
0
 
LVL 39

Accepted Solution

by:
abel earned 125 total points
ID: 24325239
There must be a point where you have first time that obj1 is created. That is where this code should go. You don't show that part of the code, so I have to assume it is somewhere else. But the syntax is equal to what I showed above:

using(SomeClass obj1 = new SomeClass())
{
    obj1.share();
    obj1.close();
    obj2.share();
    //some code here

    // you do not need to close, the using-block does it also
    // obj2.close();
}


when you "move your code to fun2" you shouldn't worry about this. I assume you mean that you pass the object to fun2. In which case, if something bad happens in fun2 the exception will unwound and will end up in the using-block where, hidden from you, the compiler generates the necessary code to cleanup and call .Close and .Dispose
0
 
LVL 9

Expert Comment

by:tculler
ID: 24325249
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.
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 39

Expert Comment

by:abel
ID: 24325551
> 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.
0
 
LVL 39

Expert Comment

by:abel
ID: 24325607
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.
0
 
LVL 9

Expert Comment

by:tculler
ID: 24326021
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.
0
 
LVL 39

Expert Comment

by:abel
ID: 24326298
> 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.
0
 
LVL 39

Expert Comment

by:abel
ID: 25237035
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
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

In a previous article published here at Experts Exchange, Signature Image with Transparent Background (http://www.experts-exchange.com/Web_Development/Document_Imaging/A_12380-Signature-Image-with-Transparent-Background.html), I explained how to cre…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
In this video, we show how to perform Bates Numbering/Stamping of PDF documents using Power PDF Advanced, the newest product from the Document Imaging division of Nuance Communications. There are two editions of Power PDF — Standard and Advanced. Th…
In this video, we show how to convert an image-only PDF file into a PDF Searchable Image file, that is, a file with both the image (typically from scanning) and text, which is created in an automated fashion with Optical Character Recognition (OCR) …

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now