Stack overflow error while disposing object – C#
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;
}
🙂
Categories: Misc
C#, Dispose, Stack overflow
Comments (0)
Trackbacks (0)
Leave a comment
Trackback