NativePool.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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.NativePool<T>* _nativePool;
  9. private const int _defaultPoolSize = 200;
  10. public NativePool(int maxPoolSize = _defaultPoolSize)
  11. {
  12. _nativePool = UnsafeType.NativePool<T>.Create(maxPoolSize);
  13. IsDisposed = false;
  14. }
  15. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  16. public T* Alloc()
  17. {
  18. return _nativePool->Alloc();
  19. }
  20. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  21. public void Return(T* ptr)
  22. {
  23. _nativePool->Return(ptr);
  24. }
  25. public void Dispose()
  26. {
  27. if (IsDisposed)
  28. {
  29. return;
  30. }
  31. if (_nativePool != null)
  32. {
  33. _nativePool->Dispose();
  34. NativeMemoryHelper.Free(_nativePool);
  35. GC.RemoveMemoryPressure(Unsafe.SizeOf<UnsafeType.NativePool<T>>());
  36. IsDisposed = true;
  37. }
  38. }
  39. public void ReInit()
  40. {
  41. if (IsDisposed)
  42. {
  43. _nativePool = UnsafeType.NativePool<T>.Create(_defaultPoolSize);
  44. IsDisposed = false;
  45. }
  46. }
  47. public bool IsDisposed { get; private set; }
  48. }
  49. }