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?
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.
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With