Skip to content

Instantly share code, notes, and snippets.

@chrisnas
Last active January 13, 2019 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisnas/334035669af99a6b1cee2810fba5a6d4 to your computer and use it in GitHub Desktop.
Save chrisnas/334035669af99a6b1cee2810fba5a6d4 to your computer and use it in GitHub Desktop.
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