Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions algorithms/data-structures/ObjectPool.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System;
using System.Collections.Concurrent;

namespace OctaneDownloadEngine
{
public class ObjectPool<T>
{
private ConcurrentBag<T> _objects;
private readonly Func<T> _objectGenerator;

public ObjectPool(Func<T> objectGenerator)
{
_objectGenerator = objectGenerator ?? throw new ArgumentNullException(nameof(objectGenerator));
_objects = new ConcurrentBag<T>();
}

public T Get() => _objects.TryTake(out T item) ? item : _objectGenerator();

public void Return(T item) => _objects.Add(item);

public void Empty()
{
_objects = null;
}
}
}