// // Licensed under the MIT License. See LICENSE file in the project root for full license information. // namespace MUnique.OpenMU.GameLogic; using System.Threading; using Microsoft.Extensions.ObjectPool; /// /// An which limits the amounts of created /// to the maximum retained objects. /// /// The type of objects to pool. internal sealed class LimitedObjectPool : DefaultObjectPool, IObjectPool where T : class { private readonly SemaphoreSlim _semaphore; /// /// Initializes a new instance of the class. /// /// The pooling policy to use. /// The maximum number of objects to create and retain in the pool. public LimitedObjectPool(IPooledObjectPolicy policy, int maximumRetained) : base(policy, maximumRetained) { this._semaphore = new SemaphoreSlim(maximumRetained, maximumRetained); } /// /// Initializes a new instance of the class. /// /// The pooling policy to use. public LimitedObjectPool(IPooledObjectPolicy policy) : base(policy, MaximumRetainedDefault) { this._semaphore = new SemaphoreSlim(MaximumRetainedDefault, MaximumRetainedDefault); } /// /// Gets the default number of maximum number of pooled objects. /// public static int MaximumRetainedDefault => Environment.ProcessorCount * 2; /// public async ValueTask GetAsync(CancellationToken cancellationToken = default) { await this._semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); return base.Get(); } /// public override T Get() { this._semaphore.Wait(); return base.Get(); } /// public override void Return(T obj) { base.Return(obj); this._semaphore.Release(); } /// public void Dispose() { this._semaphore.Dispose(); } }