Skip to content

Instantly share code, notes, and snippets.

@jnm2
Last active August 14, 2019 18:55
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 jnm2/afb28ba2b04aafc610e4ba4e31c2aa28 to your computer and use it in GitHub Desktop.
Save jnm2/afb28ba2b04aafc610e4ba4e31c2aa28 to your computer and use it in GitHub Desktop.

Nice for making sure stuff is cleaned up for methods that can throw but that give ownership to the caller on success rather than disposing:

var tempFile = new TempFile();
using var successTracker = new ConditionalDisposer(tempFile);

// Do stuff with the temporary file that involves reading from sources that may throw

successTracker.CancelDisposal();
return tempFile;
using System;
public struct ConditionalDisposer : IDisposable
{
private readonly IDisposable disposable;
private bool shouldDispose;
public ConditionalDisposer(IDisposable disposable)
{
this.disposable = disposable ?? throw new ArgumentNullException(nameof(disposable));
shouldDispose = true;
}
public void CancelDisposal() => shouldDispose = false;
public void Dispose()
{
if (!shouldDispose) return;
shouldDispose = false;
disposable.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment