| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Runtime.CompilerServices; |
| | | 4 | | using static Imagini.Logger; |
| | | 5 | | |
| | | 6 | | namespace Imagini |
| | | 7 | | { |
| | | 8 | | /// <summary> |
| | | 9 | | /// Represents a resource which can be disposed. |
| | | 10 | | /// </summary> |
| | | 11 | | public abstract class Resource |
| | | 12 | | { |
| | 306 | 13 | | private List<Resource> _children = new List<Resource>(); |
| | | 14 | | private readonly string _resourceName; |
| | | 15 | | |
| | 1 | 16 | | private static Dictionary<Type, int> s_count = new Dictionary<Type, int>(); |
| | 832 | 17 | | internal int ResourceID { get; private set; } |
| | | 18 | | |
| | 306 | 19 | | internal Resource() |
| | | 20 | | { |
| | 306 | 21 | | var type = this.GetType(); |
| | 306 | 22 | | _resourceName = type.Name; |
| | 306 | 23 | | if (!s_count.ContainsKey(type)) |
| | | 24 | | { |
| | 7 | 25 | | s_count.Add(type, 0); |
| | | 26 | | } |
| | 306 | 27 | | ResourceID = s_count[type]; |
| | 306 | 28 | | s_count[type]++; |
| | 306 | 29 | | Log.Debug("Created {name} ID {id}", _resourceName, ResourceID); |
| | 306 | 30 | | } |
| | | 31 | | |
| | | 32 | | |
| | | 33 | | /// <summary> |
| | | 34 | | /// Indicates if this resource is disposed or not. |
| | | 35 | | /// </summary> |
| | 1064 | 36 | | public bool IsDisposed { get; private set; } |
| | | 37 | | internal virtual void Destroy() |
| | | 38 | | { |
| | 220 | 39 | | if (IsDisposed) return; |
| | 259 | 40 | | _children.ForEach(c => c.Destroy()); |
| | 220 | 41 | | _children = null; |
| | 220 | 42 | | IsDisposed = true; |
| | 220 | 43 | | Log.Debug("Destroyed {name} ID {guid}", _resourceName, ResourceID); |
| | 220 | 44 | | } |
| | | 45 | | |
| | | 46 | | protected void CheckIfNotDisposed() |
| | | 47 | | { |
| | 341 | 48 | | if (IsDisposed) |
| | 0 | 49 | | throw new ObjectDisposedException(_resourceName); |
| | 341 | 50 | | } |
| | | 51 | | |
| | | 52 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 53 | | protected T NotDisposed<T>(Func<T> val) |
| | | 54 | | { |
| | 15 | 55 | | CheckIfNotDisposed(); |
| | 15 | 56 | | return val(); |
| | | 57 | | } |
| | | 58 | | |
| | | 59 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 60 | | protected void NotDisposed(Action action) |
| | | 61 | | { |
| | 237 | 62 | | CheckIfNotDisposed(); |
| | 237 | 63 | | action(); |
| | 237 | 64 | | } |
| | | 65 | | |
| | 39 | 66 | | internal void Register(Resource child) => _children.Add(child); |
| | | 67 | | |
| | 0 | 68 | | internal void Unregister(Resource child) => _children.Remove(child); |
| | | 69 | | } |
| | | 70 | | } |