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.4 KiB
C#

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);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (IsDisposed)
return;
IsDisposed = true;
Collection.ToList().ForEach(x => Remove(x));
Collection.Clear();
}
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();
}
}
}