Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To Dispose() or Not To Dispose() elements in an array of IDisposable objects?

There are lots of examples of Arrays or Lists of IDisposable objects being returned from functions in .NET. For example, Process.GetProcesses().

  • If I call that method is it my responsibility to Dispose() of all the members of the array as I iterate through them?
  • Why should it be my responsibility since I never created the objects and the array that I was given is just pointers to the objects which were created outside of my code.

I always thought it was the creator's burden to Dispose(). So what is the proper rule here?

like image 665
Denis Avatar asked Apr 07 '15 17:04

Denis


People also ask

When should I use Dispose?

The Dispose Method—Explicit Resource Cleanup Unlike Finalize, developers should call Dispose explicitly to free unmanaged resources. In fact, you should call the Dispose method explicitly on any object that implements it to free any unmanaged resources for which the object may be holding references.

What does Dispose () do in C#?

The Dispose() method The Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.

What keyword calls IDisposable Dispose?

NET calls an IDisposable object's Dispose() method once the code exits the block.

What is IDisposable interface in C implement the Dispose method?

IDisposable is an interface that contains only a single method i.e. Dispose(), for releasing unmanaged resources. IDisposable is defined in the System namespace. It provides a mechanism for releasing unmanaged resources.


1 Answers

There is no general rule. It's going to depend on the situation, and how the method in question is designed, as to whether or not "you" are responsible for disposing of objects you have access to. This is where documentation is often important to help users of the type understand their responsibilities.

I always thought it was the creator's burden to Dispose()

This cannot be strictly true. It is sometimes the case that a disposable object will out-live the lifetime of the block of code creating it. While it simplest when the creator can dispose of the object, sometimes it's simply impossible for them to be able to. When returning a disposable object from a method is one situation where it's often not be possible for the code creating the disposable object to clean it up, as it's lifetime needs to be smaller than the lifetime of the disposable object.

like image 74
Servy Avatar answered Sep 19 '22 04:09

Servy