对象池

作者: Sczlog | 来源:发表于2019-02-12 14:33 被阅读1次
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication6
{
    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, 500, (i, loopState) =>
            {
                MyClass mc = pool.GetObject();
                mc.GetValue(i);
                Thread.Sleep(500);
                // 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();
        }
    }

    public class ObjectPool<T>
    {
        private ConcurrentQueue<T> _objects;
        private Func<T> _objectGenerator;
        private static int COUNT = 0;
        private int _size;

        public ObjectPool(Func<T> objectGenerator,int size = 5)
        {
            if (objectGenerator == null) throw new ArgumentNullException("objectGenerator");
            this._size = size;
            _objects = new ConcurrentQueue<T>();
            _objectGenerator = objectGenerator;
        }

        public T GetObject()
        {
            T item = default(T);
            if (_objects.TryDequeue(out item)){
                Console.WriteLine("Here is a available resource");
                return item;
            }else
            {
                if (COUNT <= _size)
                {
                    Console.WriteLine("Here is more capacity, create a new resource");
                    COUNT++;
                    return _objectGenerator();
                }
                return GetObjectAsync().Result;
            }
        }

        private async Task<T> GetObjectAsync() {
            await Task.Run(() =>
            {
                int i = 0;
                while (_objects.Count == 0) {
                    i++;
                    Task.Delay(100);
                }
                Console.WriteLine("Pool is fullified, cannot insert new object, wait for release after " +i+" times tries");
                return;
            });
            Console.WriteLine("Here is a released resource");
            return GetObject();
        }


        public void PutObject(T item)
        {
            T temp;
            if (_objects.Count > 5)
            {
                _objects.TryDequeue(out temp);
            }
            _objects.Enqueue(item);
        }
    }

    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();
        }
    }

}

相关文章

  • Unity 类对象池资源池对象池

    类对象池 包含创建对象池,取对象池中的内容,回收。 对象管理类 因为使用加载AB包的时候可能会频繁创建类,但是ne...

  • Laya_2D示例项目使用对象池预制体的创建、位置设置和添加到父

    //使用对象池创建盒子 1.对象池的使用 对象池创建箱子 let box = Laya.Pool.getI...

  • Unity--简单的对象池

    简单的对象池分三步走: 建立对象池 拿到对象 回收对象 Test为对象池,Obj为自动回收的物体 Test.cs ...

  • 对象池

    一、对象池概述: 对于那些实例化开销比较大,并且生命周期比较短的对象,我们可以通过池就行管理。所谓池,就相当于一个...

  • 对象池

  • 对象池

    概要 看到现在,Netty之设计精妙,令人感叹。优化至极,令人发指。在高并发场景下,对象的分配的损耗是很大的,特别...

  • 对象池

    讲在前面 为什么要有对象池?我们需要一种类型的实例时候往往回去new一个这样会造成gc问题对象池根本奥义就在于一个...

  • 对象池

    UGUI 中使用的对象池 在 C:\Files\Unity\Projects\UGUITest\PackageSo...

  • 对象池

    java对象池化技术https://blog.csdn.net/tiane5hao/article/details...

  • 对象池

    using UnityEngine;using System.Collections.Generic; publi...

网友评论

      本文标题:对象池

      本文链接:https://www.haomeiwen.com/subject/seckeqtx.html