博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
object pool
阅读量:6257 次
发布时间:2019-06-22

本文共 2636 字,大约阅读时间需要 8 分钟。

///     /// 对象池    ///     /// 
public class ObjectPool
{ private readonly ConcurrentBag
_buffer; private readonly Func
_createFunc; private readonly Action
_resetFunc; public int Capacity { get; private set; } private readonly int _chunkSize; public int Count { get { return _buffer.Count; } } public ObjectPool(Func
createFunc, Action
resetFunc, int capacity = 50, int chunkSize = 10) { if (createFunc == null) { throw new ArgumentNullException("createFunc"); } if (capacity <= 0) { throw new ArgumentOutOfRangeException("capacity"); } if (chunkSize <= 0) { throw new ArgumentOutOfRangeException("chunkSize"); } this._buffer = new ConcurrentBag
(); this._createFunc = createFunc; this._resetFunc = resetFunc; this.Capacity = capacity; this._chunkSize = chunkSize; AllocateChunk(); } public T GetObject() { T obj; if (!_buffer.TryTake(out obj)) { //创建一些数据 AllocateChunk(); _buffer.TryTake(out obj); } return obj; } public void ReleaseObject(T obj) { Contract.Assume(obj != null); //超过容量了,不再需要 if (Count >= Capacity) return; if (_resetFunc != null) { _resetFunc(obj); } _buffer.Add(obj); } private void AllocateChunk() { for (int i = 0; i < _chunkSize; i++) { _buffer.Add(_createFunc()); } } }
class Program    {       staticvoid 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
pool = new ObjectPool
(() => new MyClass()); // Create a high demand for MyClass objects. Parallel.For(0, 1000000, (i, loopState) => { MyClass mc = pool.GetObject(); 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.PutObject(mc); if (cts.Token.IsCancellationRequested) loopState.Stop(); }); Console.WriteLine("Press the Enter key to exit."); Console.ReadLine(); cts.Dispose(); } }

 

转载地址:http://hixsa.baihongyu.com/

你可能感兴趣的文章
pd_ds中的hash
查看>>
买书不读是一种什么病?
查看>>
微信接口开发报错invalid credential, access_token is invalid or not latest hint
查看>>
nohup 部署springboot 使用命令
查看>>
MQ产品比较-ActiveMQ-RocketMQ
查看>>
暂时没有想好呢。
查看>>
windows服务 MVC之@Html.Raw()用法 文件流的读写 简单工厂和工厂模式对比
查看>>
PHP解析URL并得到URL中的参数
查看>>
【vue.js】绑定click事件
查看>>
字体属性
查看>>
linux的iptables和firewall的区别
查看>>
Install RabbitMQ server in CentOS 7
查看>>
Eureka的优势
查看>>
Android项目实战(一): SpannableString与SpannableStringBuilder
查看>>
idea中的language level 介绍
查看>>
CTSC 2018酱油记
查看>>
php框架排名(Laravel一直第一)
查看>>
行贿罪、受贿罪刑事辩护6大要点
查看>>
java日期格式(年月日时分秒毫秒)
查看>>
看懂UML类图
查看>>