Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to dispose of a resource which is not actually used?

i have a stupid question, but i want to hear the community here.

So here is my code:

using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) 
{ 
      return true; 
} 

My question, is it any different than:

(FtpWebResponse)request.GetResponse();
return true;

Which one is better in general? which one in terms of GC and why?

like image 478
Or A Avatar asked Jul 09 '10 16:07

Or A


People also ask

When to implement Dispose c#?

The dispose pattern is used for objects that implement the IDisposable interface, and is common when interacting with file and pipe handles, registry handles, wait handles, or pointers to blocks of unmanaged memory. This is because the garbage collector is unable to reclaim unmanaged objects.

Do you need to Dispose C#?

You never need to set objects to null in C#. The compiler and runtime will take care of figuring out when they are no longer in scope. Yes, you should dispose of objects that implement IDisposable.

Why Dispose in c#?

In the context of C#, dispose is an object method invoked to execute code required for memory cleanup and release and reset unmanaged resources, such as file handles and database connections.

What is Dispose in vb net?

Calling Dispose() will only release unmanaged resources, such as file handles, database connections, unmanaged memory, etc. It will not release garbage collected memory. Garbage collected memory will only get released at the next collection.


1 Answers

The first is better, but not in terms of GC. WebResponse implements IDisposable because it has resources that need to be released such as network connections, memory streams, etc. IDisposable is in place because you, as the consumer, know when you are done with the object and you call Dispose to notify the class you're done with it, and it is free to clean up after itself.

The using pattern really just calls Dispose under the hood. E.g. your first example is actually compiled to be this:

FtpWebResponse response = (FtpWebResponse)request.GetResponse()
try
{
}
finally
{
    ((IDisposable)response).Dispose();
}
return true;

This is separate from the garbage collector. A class could also clean up resources in the finalizer, which gets called from GC, but you should not rely on that to happen for two reasons:

  1. It could be a very long time before GC finally comes around, which means those resources are sitting there being consumed for no good reason.
  2. It might not actually clean up resources in the finalizer anyway
like image 139
Rex M Avatar answered Sep 24 '22 06:09

Rex M