// ***********************************************************************
// Assembly : Construction
// Author : flythink
// Created : 06-03-2020
//
// Last Modified By : flythink
// Last Modified On : 09-01-2020
// ***********************************************************************
//
// Copyright (c) jindongfang. All rights reserved.
//
//
// ***********************************************************************
namespace DQ.Construction.NewLook
{
using System;
using System.Collections.Concurrent;
///
/// Class ObjectPool.
///
///
public class ObjectPool
{
private readonly Func objectGenerator;
private readonly ConcurrentBag objects;
///
/// Initializes a new instance of the class.
///
/// The object generator.
/// objectGenerator
public ObjectPool(Func objectGenerator)
{
this.objectGenerator = objectGenerator ?? throw new ArgumentNullException(nameof(objectGenerator));
this.objects = new ConcurrentBag();
}
///
/// Gets this instance.
///
/// T.
public T Get() => this.objects.TryTake(out T item) ? item : this.objectGenerator();
///
/// Returns the specified item.
///
/// The item.
public void Return(T item) => this.objects.Add(item);
}
}