NativePool.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using NativeCollection.UnsafeType;
  4. namespace NativeCollection
  5. {
  6. public unsafe class NativePool<T> : INativeCollectionClass where T: unmanaged,IEquatable<T>,IPool
  7. {
  8. private UnsafeType.NativeStackPool<T>* _nativePool;
  9. private const int _defaultPoolSize = 200;
  10. private int _poolSize;
  11. public NativePool(int maxPoolSize = _defaultPoolSize)
  12. {
  13. _poolSize = maxPoolSize;
  14. _nativePool = UnsafeType.NativeStackPool<T>.Create(_poolSize);
  15. IsDisposed = false;
  16. }
  17. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  18. public T* Alloc()
  19. {
  20. return _nativePool->Alloc();
  21. }
  22. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  23. public void Return(T* ptr)
  24. {
  25. _nativePool->Return(ptr);
  26. }
  27. public void Dispose()
  28. {
  29. if (IsDisposed)
  30. {
  31. return;
  32. }
  33. if (_nativePool != null)
  34. {
  35. _nativePool->Dispose();
  36. NativeMemoryHelper.Free(_nativePool);
  37. NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<UnsafeType.NativeStackPool<T>>());
  38. IsDisposed = true;
  39. }
  40. }
  41. public void ReInit()
  42. {
  43. if (IsDisposed)
  44. {
  45. _nativePool = UnsafeType.NativeStackPool<T>.Create(_poolSize);
  46. IsDisposed = false;
  47. }
  48. }
  49. public bool IsDisposed { get; private set; }
  50. }
  51. }