Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# disposable objects

Are there some advices about how I should deal with the IDisposable object sequences?

For example, I have a method that builds a IEnumerable<System.Drawing.Image> sequence and at some point I would need to dispose that objects manually, because otherwise this might lead to some leaks.

Now, is there a way to bind the Dispose() call to garbage collector actions, because I want these objects disposed right in the moment they are no longer accessible from other code parts?

**Or maybe you could advice me some other approach? **


Generally, this seems to be the same problem as it comes, for example, in unmanaged C++ without shared pointers, where you can have a method:

SomeObject* AllocateAndConstruct();

and then you can't be sure when to dispose it, if you don't use code contracts or don't state something in the comments.

I guess the situation with disposable objects is pretty the same, but I hope there is an appropriate solution for this.

like image 310
Yippie-Ki-Yay Avatar asked Apr 26 '11 09:04

Yippie-Ki-Yay


1 Answers

(from the question)

Now, is there a way to bind the Dispose() call to garbage collector actions, because I want these objects disposed right in the moment they are no longer accessible from other code parts?

GC doesn't happen immediately when your object goes out of scope / reach; it is non-deterministic. By the time GC sees it, there is no point doing anything else (that isn't already handled by the finalizer), as it is too late.

The trick, then, is to know when you are done with it, and call Dispose() yourself. In many cases using achieves this. For example you could write a class that implements IDisposable and encapsulates a set of Images - and wrap your use of that encapsulating object with using. The Dispose() on the wrapper could Dispose() all the images held.

i.e.

using(var imageWrapper = GetImages()) {
    foreach(var image in imageWrapper) {
         ...
    }
    // etc
} // assume imageWrapper is something you write, which disposes the child items

however, this is a bit trickier if you are displaying the data on the UI. There is no shortcut there; you will have to track when you are done with each image, or accept non-deterministic finalization.

like image 60
Marc Gravell Avatar answered Nov 05 '22 13:11

Marc Gravell