forked from linkdotnet/BlogExamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectPool.cs
More file actions
21 lines (17 loc) · 704 Bytes
/
ObjectPool.cs
File metadata and controls
21 lines (17 loc) · 704 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System.Collections.Concurrent;
public class ObjectPool<T>
{
private readonly ConcurrentBag<T> _objects;
private readonly Func<T> _objectGenerator;
/// <summary>
/// Initializes the ObjectPool.
/// </summary>
/// <param name="objectGenerator">We need a generator function to create an object if our pool is empty.</param>
public ObjectPool(Func<T> objectGenerator)
{
_objectGenerator = objectGenerator ?? throw new ArgumentNullException(nameof(objectGenerator));
_objects = new ConcurrentBag<T>();
}
public T Rent() => _objects.TryTake(out T item) ? item : _objectGenerator();
public void Return(T item) => _objects.Add(item);
}