Files
Quentin Bray 6ffa63b923 Apply R# clean-up for reliability (#877)
* Apply R# clean-up for reliability

- Migrate to NUnit4 Assert.That
- Update dependencise versions
- Fix LangVersion to 9.0 (until net core migration)
- Reformat code
- Apply 'var' style (easier for refactoring)
- Remove redundant parentheses
- Add braces on every condition blocks (1 line)
- Uses new null checking patterns
- Uses AutoProperties when possible
- Uses string scalar type instead of class
- Clean usings
- Add .orig files in git ignore
- Rename some properties to respect defined conventions and US format definition
	- ID -> Id
	- BPM -> Bpm
	- Finish -> End

* Update R# settings according to the clean-up made
2026-06-22 19:52:06 +02:00

71 lines
2.0 KiB
C#

using System;
using System.Collections.Concurrent;
namespace VocaluxeLib.Utils
{
// Modified version of https://docs.microsoft.com/en-us/dotnet/standard/collections/thread-safe/how-to-create-an-object-pool
/// <summary>
/// Pool for objects.
/// </summary>
/// <typeparam name="T">Type of the objects in the pool.</typeparam>
public class CObjectPool<T>
{
private readonly ConcurrentBag<T> _Objects;
private readonly Func<T> _ObjectGenerator;
private readonly int _Poolsize;
/// <summary>
/// Create a new object pool.
/// </summary>
/// <param name="objectGenerator">Function witch generate a new object instance.</param>
/// <param name="poolSize">Number of objects to keep in the pool.</param>
public CObjectPool(Func<T> objectGenerator, int poolSize)
{
if (objectGenerator == null)
{
throw new ArgumentNullException(nameof(objectGenerator));
}
if (poolSize <= 0)
{
throw new ArgumentNullException(nameof(poolSize));
}
_Objects = new ConcurrentBag<T>();
_ObjectGenerator = objectGenerator;
_Poolsize = poolSize;
}
/// <summary>
/// Get an object (from the pool or a new one).
/// </summary>
/// <returns>An object instance.</returns>
public T GetObject()
{
T item;
if (_Objects.TryTake(out item))
{
return item;
}
return _ObjectGenerator();
}
/// <summary>
/// Put an intance back to the pool.
/// </summary>
/// <param name="item">The object instance that is given back to the pool.</param>
public void PutObject(T item)
{
if (_Objects.Count < _Poolsize)
{
_Objects.Add(item);
}
else
{
(item as IDisposable)?.Dispose();
}
}
}
}