Archived
1
0
Fork 0
This repository has been archived on 2024-05-21. You can view files and clone it, but cannot push or open issues or pull requests.
maki/Maki/BaseManager.cs

65 lines
1.5 KiB
C#
Raw Normal View History

2017-10-13 20:05:50 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
namespace Maki
{
internal abstract class BaseManager<T> : IDisposable
{
protected readonly HashSet<T> Collection = new HashSet<T>();
public IEnumerable<T> Items => Collection;
public int Count => Collection.Count;
public event Action<T> OnAdd;
public event Action<T> OnRemove;
protected virtual bool DisposeOnRemove => true;
protected bool IsDisposed = false;
~BaseManager()
=> Dispose(false);
public void Dispose()
=> Dispose(true);
2017-10-13 20:05:50 +00:00
protected void Dispose(bool disposing)
{
if (IsDisposed)
return;
IsDisposed = true;
Collection.ToList().ForEach(x => Remove(x));
Collection.Clear();
if (disposing)
GC.SuppressFinalize(this);
2017-10-13 20:05:50 +00:00
}
public virtual void Add(T item)
{
if (item == null)
return;
lock (Collection)
Collection.Add(item);
OnAdd?.Invoke(item);
}
public virtual void Remove(T item)
{
if (item == null)
return;
lock (Collection)
Collection.Remove(item);
OnRemove?.Invoke(item);
if (DisposeOnRemove && item is IDisposable)
(item as IDisposable).Dispose();
}
}
}