Reputation: 1
I have a question on the write syntx to implement the Dispose inside my asp.net mvc-5 web application.
now i created a new asp.net mvc-5 web application using Visual Studio 2013 , and i mapped my database tables inside an edmx file. then i created a new Controller class. now the default code for Dispose()
is as follow at the end of the controller class:-
public class DeptsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
//code goes here..
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
but at the same time i find many online articles and books which use the following syntax to Dispose the current request as in this link:-
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
so i have this question :- which syntax for dispose i should/prefer to use ? and do these 2 approaches generate the same result ?
Upvotes: 1
Views: 730
Reputation: 1332
When you implement IDisposble, just use the implementation that visual studio will build. The comments in the generated code tell you exactly when you do and do not need to call the GC. Example of the generated code:
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~ChampionGgCallerHttpClient() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
Upvotes: 0
Reputation: 52250
If your class has a ~DeptsController
method (a.k.a a finalize method or "destructor"), and all it does is call Dispose()
, you need to call GC.SuppressFinalize(this)
to prevent Dispose
from being called twice.
If your class does not have a destructor then there is no need.
Upvotes: 1