Last active
January 13, 2019 15:11
-
-
Save chrisnas/334035669af99a6b1cee2810fba5a6d4 to your computer and use it in GitHub Desktop.
This file contains 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 LargeObject : IDisposable | |
{ | |
... | |
class NativeState | |
{ | |
public bool _disposed; | |
public IntPtr _handle1; | |
public IntPtr _handle2; | |
} | |
private NativeState _state; | |
// Plus some heavy stuff that we don't want to keep around once the object | |
// is no more referenced | |
public LargeObject() | |
{ | |
_state = new NativeState() | |
{ | |
_handle1 = (IntPtr) (DateTime.Now.Ticks), | |
_handle2 = (IntPtr) (DateTime.Now.Ticks + 1), | |
}; | |
// this is where we imagine using a PhantomObjectFinalizer | |
} | |
public void Dispose() | |
{ | |
if (_state._disposed) | |
return; | |
Cleanup(_state); | |
CleanupIDisposableFields(); | |
} | |
private void CleanupIDisposableFields() | |
{ | |
// call Dispose on all IDisposable fields | |
} | |
private static void Cleanup(NativeState state) | |
{ | |
if (state._disposed) | |
return; | |
state._disposed = true; | |
Console.WriteLine($"cleanup native resource {state._handle1.ToString()}"); | |
Console.WriteLine($"cleanup native resource {state._handle2.ToString()}"); | |
throw new InvalidOperationException("I messed up the cleaning..."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment