Cesium for Unity 1.15.2
Loading...
Searching...
No Matches
CesiumObjectPool.cs
Go to the documentation of this file.
1using System;
2using System.Collections.Generic;
3
4namespace CesiumForUnity
5{
6 internal class CesiumObjectPool<T> : IDisposable where T : class
7 {
8 private List<T> _pool;
9 private int _maximumSize;
10 private Func<T> _createCallback;
11 private Action<T> _releaseCallback;
12 private Action<T> _destroyCallback;
13
14 public CesiumObjectPool(Func<T> createCallback, Action<T> releaseCallback, Action<T> destroyCallback, int maximumSize = 1000)
15 {
16 this._pool = new List<T>(maximumSize);
17 this._maximumSize = maximumSize;
18 this._createCallback = createCallback;
19 this._releaseCallback = releaseCallback;
20 this._destroyCallback = destroyCallback;
21 }
22
23 public void Dispose()
24 {
25 this.Clear();
26
27 // A null pool indicates released objects should be freed,
28 // rather than added back into the pool.
29 this._pool = null;
30 }
31
32 public int CountInactive => this._pool.Count;
33
34 public void Clear()
35 {
36 if (this._pool == null)
37 return;
38
39 foreach (T o in this._pool)
40 {
41 this._destroyCallback(o);
42 }
43 }
44
45 public T Get()
46 {
47 if (this._pool != null && this._pool.Count > 0)
48 {
49 int pos = this._pool.Count - 1;
50 T result = this._pool[pos];
51 this._pool.RemoveAt(pos);
52 return result;
53 }
54 else
55 {
56 return this._createCallback();
57 }
58 }
59
60 public void Release(T element)
61 {
62 this._releaseCallback(element);
63
64 if (this._pool != null && this._pool.Count < this._maximumSize)
65 {
66 this._pool.Add(element);
67 }
68 else
69 {
70 this._destroyCallback(element);
71 }
72 }
73 }
74}