Created
August 15, 2018 23:33
-
-
Save Ariex/c8e0cc246bf2150b61fc6cc14aea8db7 to your computer and use it in GitHub Desktop.
An object pool with size fixed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FixSizedObjectPool<T> | |
{ | |
protected Func<T> Generator; | |
protected ConcurrentBag<T> ObjectBag; | |
protected int MaxSize; | |
protected long createdInstanceCount = 0; | |
protected SemaphoreSlim Pool; | |
public FixSizedObjectPool(Func<T> objectGenerator, int maxSize) | |
{ | |
this.Generator = objectGenerator; | |
this.MaxSize = maxSize; | |
this.Pool = new SemaphoreSlim(0, maxSize); | |
this.ObjectBag = new ConcurrentBag<T>(); | |
} | |
public async Task<T> GetObject() | |
{ | |
T item; | |
if (Interlocked.Increment(ref createdInstanceCount) <= MaxSize) | |
{ | |
return this.Generator(); | |
} | |
else | |
{ | |
Interlocked.Decrement(ref createdInstanceCount); | |
await Pool.WaitAsync(); | |
if (this.ObjectBag.TryTake(out item)) | |
{ | |
return item; | |
} | |
else | |
{ | |
return await GetObject(); | |
} | |
} | |
} | |
public void PutObject(T obj) | |
{ | |
this.ObjectBag.Add(obj); | |
Pool.Release(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this is modified from: https://docs.microsoft.com/en-us/dotnet/standard/collections/thread-safe/how-to-create-an-object-pool, and tested with following code