You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
|
// ***********************************************************************
|
|
|
|
|
|
// Assembly : Construction
|
|
|
|
|
|
// Author : flythink
|
|
|
|
|
|
// Created : 06-03-2020
|
|
|
|
|
|
//
|
|
|
|
|
|
// Last Modified By : flythink
|
|
|
|
|
|
// Last Modified On : 09-01-2020
|
|
|
|
|
|
// ***********************************************************************
|
|
|
|
|
|
// <copyright file="ObjectPool.cs" company="jindongfang">
|
|
|
|
|
|
// Copyright (c) jindongfang. All rights reserved.
|
|
|
|
|
|
// </copyright>
|
|
|
|
|
|
// <summary></summary>
|
|
|
|
|
|
// ***********************************************************************
|
|
|
|
|
|
|
|
|
|
|
|
namespace WellWorkDataUI
|
|
|
|
|
|
{
|
|
|
|
|
|
using System;
|
|
|
|
|
|
using System.Collections.Concurrent;
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// Class ObjectPool.
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <typeparam name="T"></typeparam>
|
|
|
|
|
|
public class ObjectPool<T>
|
|
|
|
|
|
{
|
|
|
|
|
|
private readonly Func<T> objectGenerator;
|
|
|
|
|
|
|
|
|
|
|
|
private readonly ConcurrentBag<T> objects;
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// Initializes a new instance of the <see cref="ObjectPool{T}" /> class.
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <param name="objectGenerator">The object generator.</param>
|
|
|
|
|
|
/// <exception cref="ArgumentNullException">objectGenerator</exception>
|
|
|
|
|
|
public ObjectPool(Func<T> objectGenerator)
|
|
|
|
|
|
{
|
|
|
|
|
|
this.objectGenerator = objectGenerator ?? throw new ArgumentNullException(nameof(objectGenerator));
|
|
|
|
|
|
this.objects = new ConcurrentBag<T>();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// Gets this instance.
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <returns>T.</returns>
|
|
|
|
|
|
public T Get() => this.objects.TryTake(out T item) ? item : this.objectGenerator();
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// Returns the specified item.
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <param name="item">The item.</param>
|
|
|
|
|
|
public void Return(T item) => this.objects.Add(item);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|