Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference of Response.Close() and Response.Dispose()?

From the resource clean-up perspective, why there are Response.Close() and Response.Dispose() and which one is more comprehensive (call the other one) ?

like image 834
Xaqron Avatar asked Jan 21 '23 20:01

Xaqron


2 Answers

Where both methods are provided the implementation of Dispose should call Close. It is a good idea to use the using statement to ensure that Disposeand therefore Close is called, even if there is an exception.

In other words do this:

using (Response response = ...)
{
    // ...
}

Not this:

Response response = ...;
// ...
response.Close(); // If there is an exception this might never get called!

One difference between closing and disposing an object is that when you dispose an object it usually is not possible to use the object any more (attempting to do so may cause an ObjectDisposedException to be thrown), but after calling Close it may be possible to still use the object.

Note that if you are talking about ASP.NET then you shouldn't normally call Close or Dispose on the Response object.

like image 125
Mark Byers Avatar answered Mar 28 '23 15:03

Mark Byers


From the Design Guidelines for Developing Class Library on Implementing Finalize and Dispose to Clean Up Unmanaged Resources

Occasionally a domain-specific name is more appropriate than Dispose. For example, a file encapsulation might want to use the method name Close. In this case, implement Dispose privately and create a public Close method that calls Dispose. The following code example illustrates this pattern. You can replace Close with a method name appropriate to your domain. This example requires the System namespace.

/ Do not make this method virtual.
// A derived class should not be allowed
// to override this method.
public void Close()
{
   // Call the Dispose method with no parameters.
   Dispose();
}

Typically I've seen close whenever the resource can be opened or re-opened, since it gives nice symmetry to the method names.

like image 21
Conrad Frix Avatar answered Mar 28 '23 14:03

Conrad Frix