Delegate Disposable
29-12-2015 12:08:52
C# / Utilities
0 Bookmark(s)
366 View(s)
The delegate disposable is a reusable implementation of the IDisposable interface. It calls the action that is passed in the constructor, when the object is disposed.
public class DelegateDisposable : IDisposable
{
private readonly Action _disposeAction;
public DelegateDisposable(Action disposeAction)
{
_disposeAction = disposeAction;
}
public void Dispose()
{
_disposeAction();
}
}
Example usage:
IDisposable BeginTransaction()
{
Console.Log("Transaction started...");
return new DelegateDisposable(() => Console.Log("Transaction ended..."));
}
using(var transaction = BeginTransaction())
{
// Do something
}