ASP.NET Core 中的 ObjectPool 对象重用(二)
前言
上一篇文章主要介绍了objectpool的理论知识,再来介绍一下microsoft.extensions.objectpool是如何实现的.
核心组件
objectpool
objectpool是一个泛型抽象接口,他抽象了两个方法get和return
- get方法用于从对象池获取到可用对象,如果对象不可用则创建对象并返回出来
- return方法用户将对象返回到对象池
/// <summary> /// a pool of objects. /// </summary> /// <typeparam name="t">the type of objects to pool.</typeparam> public abstract class objectpool<t> where t : class { /// <summary> /// gets an object from the pool if one is available, otherwise creates one. /// </summary> /// <returns>a <typeparamref name="t"/>.</returns> public abstract t get(); /// <summary> /// return an object to the pool. /// </summary> /// <param name="obj">the object to add to the pool.</param> public abstract void return(t obj); }
objectpoolprovider
objectpoolprovider是一个抽象接口他内置了create的泛型方法和create的泛型抽象方法,他是一个基于默认策略的。
/// <summary> /// a provider of <see cref="objectpool{t}"/> instances. /// </summary> public abstract class objectpoolprovider { /// <summary> /// creates an <see cref="objectpool"/>. /// </summary> /// <typeparam name="t">the type to create a pool for.</typeparam> public objectpool<t> create<t>() where t : class, new() { return create<t>(new defaultpooledobjectpolicy<t>()); } /// <summary> /// creates an <see cref="objectpool"/> with the given <see cref="ipooledobjectpolicy{t}"/>. /// </summary> /// <typeparam name="t">the type to create a pool for.</typeparam> public abstract objectpool<t> create<t>(ipooledobjectpolicy<t> policy) where t : class; }
ipooledobjectpolicy
ipooledobjectpolicy是一个泛型接口,提供策略管理对象池,该类也定义了两个方法create和return以提供策略实现
- create用于创建相关的类实例
- return用于将已经使用完的对象放回到池中,包括重置对象状态以及是否能够放回到池中
/// <summary> /// represents a policy for managing pooled objects. /// </summary> /// <typeparam name="t">the type of object which is being pooled.</typeparam> public interface ipooledobjectpolicy<t> { /// <summary> /// create a <typeparamref name="t"/>. /// </summary> /// <returns>the <typeparamref name="t"/> which was created.</returns> t create(); /// <summary> /// runs some processing when an object was returned to the pool. can be used to reset the state of an object and indicate if the object should be returned to the pool. /// </summary> /// <param name="obj">the object to return to the pool.</param> /// <returns><code>true</code> if the object should be returned to the pool. <code>false</code> if it's not possible/desirable for the pool to keep the object.</returns> bool return(t obj); }
pooledobjectpolicy是一个泛型抽象类,并且实现了ipooledobjectpolicy,对外提供了两个抽象方法
public abstract class pooledobjectpolicy<t> : ipooledobjectpolicy<t> { public abstract t create(); public abstract bool return(t obj); }
实现机制
defaultobjectpool
defaultobjectpool实现了objectpool,interlocked.compareexchange(ref _firstitem, null, item)将_firstitem的值和item的值比较,相等则用null替换_firstitem,否则不操作,不管替换还是不替换返回的都是原来保存在_firstitem的值。
interlocked可以为多个线程共享的变量提供原子操作。
- interlocked.increment:以原子操作的形式递增指定变量的值并存储结果。
- interlocked.decrement以原子操作的形式递减指定变量的值并存储结果。
- interlocked.add以原子操作的形式,添加两个整数并用两者的和替换第一个整数
public override t get() { var item = _firstitem; if (item == null || interlocked.compareexchange(ref _firstitem, null, item) != item) { var items = _items; for (var i = 0; i < items.length; i++) { item = items[i].element; if (item != null && interlocked.compareexchange(ref items[i].element, null, item) == item) { return item; } } item = create(); } return item; } public override void return(t obj) { if (_isdefaultpolicy || (_fastpolicy?.return(obj) ?? _policy.return(obj))) { if (_firstitem != null || interlocked.compareexchange(ref _firstitem, obj, null) != null) { var items = _items; for (var i = 0; i < items.length && interlocked.compareexchange(ref items[i].element, obj, null) != null; ++i) { } } } }
defaultobjectpoolprovider
defaultobjectpoolprovider重写了objectpoolprovider中crearte方法,
设置了默认的对象最大数量只能用的是默认的environment.processorcount * 2(cpu处理器的两倍)
/// <summary> /// the default <see cref="objectpoolprovider"/>. /// </summary> public class defaultobjectpoolprovider : objectpoolprovider { /// <summary> /// the maximum number of objects to retain in the pool. /// </summary> public int maximumretained { get; set; } = environment.processorcount * 2; /// <inheritdoc/> public override objectpool<t> create<t>(ipooledobjectpolicy<t> policy) { if (policy == null) { throw new argumentnullexception(nameof(policy)); } if (typeof(idisposable).isassignablefrom(typeof(t))) { return new disposableobjectpool<t>(policy, maximumretained); } return new defaultobjectpool<t>(policy, maximumretained); } }
disposableobjectpool
disposableobjectpool继承了defaultobjectpool以及实现了idisposable用于手动的回收对象
public void dispose() { _isdisposed = true; disposeitem(_firstitem); _firstitem = null; objectwrapper[] items = _items; for (var i = 0; i < items.length; i++) { disposeitem(items[i].element); items[i].element = null; } } private void disposeitem(t item) { if (item is idisposable disposable) { disposable.dispose(); } }
leaktrackingobjectpool
leaktrackingobjectpool实现了objectpool,它定义了conditionalweaktable他是一个弱引用字典,conditionalweaktable<tkey,tvalue> 中的所有 key 和所有的 value 都是弱引用的,并且会在其 key 被回收或者 key 和 value 都被回收之后自动从集合中消失。这意味着当你使用它来为一个类型附加一些字段或者属性的时候完全不用担心内存泄漏的问题
public class leaktrackingobjectpool<t> : objectpool<t> where t : class { private readonly conditionalweaktable<t, tracker> _trackers = new conditionalweaktable<t, tracker>(); private readonly objectpool<t> _inner; public leaktrackingobjectpool(objectpool<t> inner) { if (inner == null) { throw new argumentnullexception(nameof(inner)); } _inner = inner; } public override t get() { var value = _inner.get(); _trackers.add(value, new tracker()); return value; } public override void return(t obj) { tracker tracker; if (_trackers.trygetvalue(obj, out tracker)) { _trackers.remove(obj); tracker.dispose(); } _inner.return(obj); } private class tracker : idisposable { private readonly string _stack; private bool _disposed; public tracker() { _stack = environment.stacktrace; } public void dispose() { _disposed = true; gc.suppressfinalize(this); } ~tracker() { if (!_disposed && !environment.hasshutdownstarted) { debug.fail($"{typeof(t).name} was leaked. created at: {environment.newline}{_stack}"); } } } }
参考
推荐阅读
-
ASP.NET Core 中的 ObjectPool 对象重用(二)
-
Asp.net Core MVC中怎么把二级域名绑定到特定的控制器上
-
ASP.NET Core 中的 ObjectPool 对象重用(一)
-
ASP.NET Core 中的 ObjectPool 对象重用(二)
-
(12)ASP.NET Core 中的配置二(Configuration)
-
Asp.net Core MVC中怎么把二级域名绑定到特定的控制器上
-
(9)ASP.NET Core 中的MVC路由(二)
-
(12)ASP.NET Core 中的配置二(Configuration)
-
ASP.NET Core 中的 ObjectPool 对象重用(一)
-
asp.net core mvc中如何把二级域名绑定到特定的控制器上