mcu
mcu

Reputation: 3512

Disposing of IDisposable Without Reference

Sometimes an instance of a class that implements Dispose() is used without actually retaining any reference to the instance.

What should be done regarding garbage collection in this case?

Example:

MsgBox(New System.Net.WebClient().DownloadString("http://www.website.com"))

WebClient implements Dispose().

Please feel free to rename the subject as you see fit.

Upvotes: 0

Views: 118

Answers (2)

supercat
supercat

Reputation: 81277

Only in very rare cases should properly-written code ever allow all references to a resource-holding object be abandoned without Dispose having been called on it first. In addition to problems resulting from delayed cleanup, careless handling of IDisposable objects can also in some cases result in early cleanup.

For example, suppose one has a class Widget which uses some sort of native handle to a Widget, and it has a method

void Woozle()
{
  NativeWidget.Woozle(myWidget));
}

If the very last thing which is done with a Widget before abandonment is to call Woozle, the GC may notice that it fetches the value of myWidget, none of the fields of that Widget can ever be accessed again and thus nobody should notice if it disappears. Because garbage-collection is an asynchronous process, that could happen even while the Woozle method is running. If Widget has a destructor or Finalize method that releases the myWidget resource, the results could be disastrous.

If, by contrast, the Widget reference had been kept around for purpose of calling Dispose on it, and Dispose does either GC.SuppressFinalize or GC.KeepAlive, then there's no possibility of the finalizer running until after the call to Woozle is complete.

Upvotes: 1

usr
usr

Reputation: 171246

Here, you should refactor the code so that disposal happens. That is exceedingly easy thanks to the Using statement.

I do now know why WebClient needs to be disposed. In simple use cases it does not hold onto any resource as far as I can tell.

This issue has nothing to do with the GC. This object will be cleaned up like any other object when the GC finds it unreferenced.

Upvotes: 2

Related Questions