Micosoft.Extension.ObjectPool 源碼架構、模式分析: 三大基本對象: 1. ObjectPool抽象類 2. ObjectPoolProvider抽象類 3. IPooledObjectPolicy介面 ObjectPool的預設實現是DefaultPool,對象池的創建 ...
Micosoft.Extension.ObjectPool
源碼架構、模式分析:
三大基本對象:
- ObjectPool抽象類
- ObjectPoolProvider抽象類
- IPooledObjectPolicy介面
ObjectPool的預設實現是DefaultPool,對象池的創建由ObjectPoolProvider抽象類的預設實現DefaultObjectPoolProvider類實現。
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);
}
}
IPooledObjectPolicy介面有對應的抽象類及預設實現,對象池中的對象(也就是池對象)的創建或返回由此策略類來控制。
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;
}
// Non-inline to improve its code quality as uncommon path
[MethodImpl(MethodImplOptions.NoInlining)]
private T Create() => _fastPolicy?.Create() ?? _policy.Create();
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)
{
}
}
}
}
==從整體的設計思路來說,提供者Provider用來提供具體的對象池,傳入的參數也是策略類,而策略類則把控池對象的具體處理。dotnet core中很多源碼的開發模式都是這種:通過Policy構建Provider,通過Provider創建最終的類。也就是說,只通過策略類來實現自定義擴展,這種架構可以借鑒和思考。==
官方實現:
Object reuse with ObjectPool in ASP.NET Core
參考示例:
.NET Core 3.0之深入源碼理解ObjectPool(二)