ConcurrentPool.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Pool to avoid allocations (from libuv2k)
  2. // API consistent with Microsoft's ObjectPool<T>.
  3. // concurrent for thread safe access.
  4. //
  5. // currently not in use. keep it in case we need it again.
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Runtime.CompilerServices;
  9. namespace Mirror
  10. {
  11. public class ConcurrentPool<T>
  12. {
  13. // Mirror is single threaded, no need for concurrent collections
  14. // concurrent bag is for items who's order doesn't matter.
  15. // just about right for our use case here.
  16. readonly ConcurrentBag<T> objects = new ConcurrentBag<T>();
  17. // some types might need additional parameters in their constructor, so
  18. // we use a Func<T> generator
  19. readonly Func<T> objectGenerator;
  20. public ConcurrentPool(Func<T> objectGenerator, int initialCapacity)
  21. {
  22. this.objectGenerator = objectGenerator;
  23. // allocate an initial pool so we have fewer (if any)
  24. // allocations in the first few frames (or seconds).
  25. for (int i = 0; i < initialCapacity; ++i)
  26. objects.Add(objectGenerator());
  27. }
  28. // take an element from the pool, or create a new one if empty
  29. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  30. public T Get() => objects.TryTake(out T obj) ? obj : objectGenerator();
  31. // return an element to the pool
  32. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  33. public void Return(T item) => objects.Add(item);
  34. // count to see how many objects are in the pool. useful for tests.
  35. public int Count => objects.Count;
  36. }
  37. }