在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
一、什么是对象池
public class ObjectPool<T> : IObjectPool<T> { private Func<T> _instanceFactory; private ConcurrentBag<T> _instanceItems; public ObjectPool(Func<T> instanceFactory) { _instanceFactory = instanceFactory ?? throw new ArgumentNullException(nameof(instanceFactory)); _instanceItems = new ConcurrentBag<T>(); } public T Get() { T item; if (_instanceItems.TryTake(out item)) return item; return _instanceFactory(); } public void Return(T item) { _instanceItems.Add(item); } } 二、.NET Core 中的对象池在 具体代码如下: 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) { } } } } 这里用到 说了这么多,我们来看一下对象池具体的用法: var service = new ServiceCollection(); //使用DefaultObjectPoolProvider service.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>(); //使用默认策略 service.AddSingleton<ObjectPool<Foo>>(serviceProvider => { var objectPoolProvider = serviceProvider.GetRequiredService<ObjectPoolProvider>(); return objectPoolProvider.Create<Foo>(); }); //使用自定义策略 service.AddSingleton<ObjectPool<Foo>>(serviceProvider => { var objectPoolProvider = serviceProvider.GetRequiredService<ObjectPoolProvider>(); return objectPoolProvider.Create(new FooObjectPoolPolicy()); }); var serviceProvider = _service.BuildServiceProvider(); var objectPool = _serviceProvider.GetService<ObjectPool<Foo>>(); //有借有还,两次是同一个对象 var item1 = objectPool.Get(); objectPool.Return(item1); var item2 = objectPool.Get(); Assert.AreEqual(item1, item2);//true //有借无还,两次是不同的对象 var item3 = objectPool.Get(); var item4 = objectPool.Get(); Assert.AreEqual(item3, item4);//false 上面的代码中Foo和FooObjectPoolPolicy是两个工具类: public class Foo { public string Id { get; set; } public DateTime? CreatedAt { get; set; } public string CreatedBy { get; set; } } public class FooObjectPoolPolicy : IPooledObjectPolicy<Foo> { public Foo Create() { return new Foo() { Id = Guid.NewGuid().ToString("N"), CreatedAt = DateTime.Now, CreatedBy = "zs" }; } public bool Return(Foo obj) { return true; } } TIP:当你需要控制对象池内的对象如何被创建的时候,你可以考虑实现自定义的 三、本文小结实现对象池可以考虑
到此这篇关于 .NET Core 中对象池 Object Pool的使用的文章就介绍到这了,更多相关 .NET Core 中对象池 内容请搜索极客世界以前的文章或继续浏览下面的相关文章希望大家以后多多支持极客世界! |
请发表评论