Search code examples
c#collectionsdisposedisposable

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.


Solution

  • You should design your system in a way that you know when the resources are no longer needed. In the worst case, they'll be eventually disposed when the garbage collector gets to it, but the point of IDisposable is that you can release important resources earlier.

    This "earlier" is up to you to define, for example, you can release them when the window that's using them closes, or when your unit of work finishes doing whatever operations on them. But at some point, some object should "own" these resources, and therefore should know when they're no longer needed.