查看原文
其他

ASP.NET Core 中的 ObjectPool 对象重用

DotNet 2021-09-23

(给DotNet加星标,提升.Net技能

转自:冯辉
cnblogs.com/yyfh/p/11974574.html

前言


对象池是一种设计模式,一个对象池包含一组已经初始化过且可以使用的对象,而可以在有需求时创建和销毁对象。池的对象可以从池中取得对象,对其进行操作处理,并在不需要时归还给池子而非直接销毁他,他是一种特殊的工厂对象。


若初始化、实例化的代价高,且有需求需要经常实例化,但每次实例化的数量较小的情况下,使用对象池可以过得显著的性能提升。从池子中取得对象的时间是可测的,但新建一个实际所需要的时间是不确定的。





public class ObjectPool<T>
{
private ConcurrentBag<T> _object;
private Func<T> _objectGenerator;
public ObjectPool(Func<T> objectGenerator) {
_object = new ConcurrentBag<T>();
_objectGenerator = objectGenerator;
}
/// <summary>
/// 取出
/// </summary>
/// <returns></returns>
public T CheckOut() {
T item;
if (_object.TryTake(out item)) return item;
return _objectGenerator();
}
/// <summary>
/// 归还
/// </summary>
/// <param name="obj"></param>
public void CheckIn(T obj) {
_object.Add(obj);
}
}


测试


class Program
{
static void Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
// Create an opportunity for the user to cancel.
Task.Run(() =>
{
if (Console.ReadKey().KeyChar == 'c' || Console.ReadKey().KeyChar == 'C')
cts.Cancel();
});
ObjectPool<MyClass> pool = new ObjectPool<MyClass>(() => new MyClass());
// Create a high demand for MyClass objects.
Parallel.For(0, 1000000, (i, loopState) =>
{
MyClass mc = pool.CheckOut();
Console.CursorLeft = 0;
// This is the bottleneck in our application. All threads in this loop
// must serialize their access to the static Console class.
Console.WriteLine("{0:####.####}", mc.GetValue(i));
pool.CheckIn(mc);
if (cts.Token.IsCancellationRequested)
loopState.Stop();
});
Console.WriteLine("Press the Enter key to exit.");
Console.ReadLine();
cts.Dispose();
}
class MyClass
{
public int[] Nums { get; set; }
public double GetValue(long i)
{
return Math.Sqrt(Nums[i]);
}
public MyClass()
{
Nums = new int[1000000];
Random rand = new Random();
for (int i = 0; i < Nums.Length; i++)
Nums[i] = rand.Next();
}
}
}



推荐阅读

(点击标题可跳转阅读)

.NET Core使用Ocelot网关 鉴权认证

命令创建.NET Core 3.0 Web应用详解

鲲鹏来了,在EulerOS试用.NET Core-3.1


看完本文有收获?请转发分享给更多人

关注「DotNet」加星标,提升.Net技能 

好文章,我在看❤️

: . Video Mini Program Like ,轻点两下取消赞 Wow ,轻点两下取消在看

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存