Advertisements

Archive

Posts Tagged ‘Dispose’

Stack overflow error while disposing object – C#

September 27, 2014 Leave a comment

I have a class “ABC” which implements “IDisposable” interface and having below Dispose method.

Public Class ABC : IDisposable {

public void Dispose()       {

this.Dispose(true);

}

}

When I run the application I was getting “Stack Overflow” error because the Dispose() method getting called recursively and went in to an infinite loop.

Fix :

  • Prevent the Dispose() recursive call by using flag and the logic is as below

 private bool disposed = false;

public void Dispose() {

this.Dispose(true);

GC.SuppressFinalize(this);

}

protected virtual void Dispose(bool disposing) {

if (this.disposed) {

return;

}

this.disposed = true;

}

🙂

Advertisements
Categories: Misc Tags: , ,