Skip to content

Instantly share code, notes, and snippets.

@pmunin
Last active April 17, 2017 18:52
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 pmunin/e09ba0eacbbc31e28d6e to your computer and use it in GitHub Desktop.
Save pmunin/e09ba0eacbbc31e28d6e to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
namespace DisposeUtils
{
/// <summary>
/// Util class for implementing disposable using delegates.
/// Latest version is here: https://gist.github.com/pmunin/e09ba0eacbbc31e28d6e
/// </summary>
public class DisposeAction : IDisposable
{
public DisposeAction(IEnumerable<Action> onDisposeEnumerable)
{
this.onDisposeActions = onDisposeEnumerable;
}
public DisposeAction(params Action[] onDisposeArray) : this(onDisposeEnumerable: onDisposeArray)
{
}
public DisposeAction(Action<DisposeAction> config)
{
config(this);
}
IEnumerable<Action> onDisposeActions;
public void OnDispose(Action onDispose, bool first = false)
{
var lstActions = OnDisposeActionList();
if (first)
lstActions.Insert(0, onDispose);
else
lstActions.Add(onDispose);
}
List<Action> OnDisposeActionList()
{
var res = onDisposeActions as List<Action>;
if (res == null)
{
onDisposeActions = res = onDisposeActions == null ? new List<Action>() : new List<Action>(onDisposeActions);
}
return res;
}
public void Dispose()
{
if (onDisposeActions != null)
foreach (var da in onDisposeActions)
{
da?.Invoke();
}
}
}
public static class DisposeExtensions
{
/// <summary>
/// Returns new Disposable, that dispose this disposable and all other specified together
/// </summary>
/// <param name="disposableToCombineWith"></param>
/// <param name="disposables"></param>
/// <returns></returns>
public static IDisposable Combine(this IDisposable disposableToCombineWith, params IDisposable[] disposables)
{
var lstActions = new List<Action>(disposables.Select<IDisposable, Action>(d => () => d?.Dispose()));
lstActions.Insert(0, () => disposableToCombineWith?.Dispose());
return new DisposeAction(lstActions);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment