Added size limit to pool.

This commit is contained in:
Harrison Deng 2020-07-11 11:18:16 -05:00
parent ab58480434
commit 326d97bd64

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using SlatedGameToolkit.Framework.Exceptions;
namespace SlatedGameToolkit.Framework.Utilities.Collections.Pooling namespace SlatedGameToolkit.Framework.Utilities.Collections.Pooling
{ {
@ -23,6 +24,7 @@ namespace SlatedGameToolkit.Framework.Utilities.Collections.Pooling
} }
public void CreateAmount(int amount) { public void CreateAmount(int amount) {
if (Size >= 0 && Count + amount >= Size) throw new FrameworkUsageException(string.Format("Object pool surpassed set size of {0}", Size));
for (int i = 0; i < amount; i++) { for (int i = 0; i < amount; i++) {
pool.Add(creator()); pool.Add(creator());
} }
@ -30,7 +32,7 @@ namespace SlatedGameToolkit.Framework.Utilities.Collections.Pooling
public Poolable Retrieve() { public Poolable Retrieve() {
if (pool.Count == 0) { if (pool.Count == 0) {
pool.Add(creator()); CreateAmount(1);
} }
Poolable result; Poolable result;
pool.TryTake(out result); pool.TryTake(out result);
@ -38,6 +40,7 @@ namespace SlatedGameToolkit.Framework.Utilities.Collections.Pooling
} }
public void Release(Poolable poolable) { public void Release(Poolable poolable) {
if (Size >= 0 && Count + 1 >= Size) throw new FrameworkUsageException(string.Format("Object pool surpassed set size of {0}", Size));
poolable.Reset(); poolable.Reset();
pool.Add(poolable); pool.Add(poolable);
} }