Last active
July 16, 2025 16:05
-
-
Save Hafthor/94e03b74bf5b1d78b14abd4ea073d958 to your computer and use it in GitHub Desktop.
Why you shouldn't call GC.SuppressFinalize(this) unless you directly have a finalizer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyClass : MyDerivedClass { | |
public override void Dispose() { | |
base.Dispose(); | |
GC.SuppressFinalize(this); // here we improperly call GC.SuppressFinalize(this) | |
} | |
} | |
public class MyDerivedClass : MyBaseClass { | |
public override void Dispose() { | |
; // oops, we forgot to call base.Dispose(); | |
} | |
} | |
public class MyBaseClass : IDisposable { | |
public virtual void Dispose() { | |
// here we properly call GC.SuppressFinalize because we have a finalizer | |
GC.SuppressFinalize(this); | |
// but this dispose method will never get called | |
} | |
~MyBaseClass() { | |
; // and this finalize will never run now because MyClass.Dispose suppressed it :( | |
} | |
} | |
// Overall, the benefit to calling GC.SuppressFinalize in the derived class is neglible if | |
// somehow the base class didn't do it, but the drawback to doing it when you don't own the | |
// unmanaged resource protected by the finalizer could be huge. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment