public void KeyedSharedPoolTest() { var allocations = new List <int>(); var pool = new KeyedSharedPool <byte[], int>( size => { allocations.Add(size); // to track allocations return(new byte[size]); }, 1); // allocate and release a 10-byte array var byte10 = pool.GetOrCreate(10); Assert.AreEqual(10, byte10.Resource.Length); Assert.AreEqual(1, allocations.Count); // new allocation Assert.AreEqual(10, allocations[0]); byte10.Dispose(); // allocate and release a 20-byte array var byte20 = pool.GetOrCreate(20); Assert.AreEqual(20, byte20.Resource.Length); Assert.AreEqual(2, allocations.Count); // new allocation Assert.AreEqual(20, allocations[1]); byte20.Dispose(); // request another 10-byte array without releasing byte10 = pool.GetOrCreate(10); Assert.AreEqual(10, byte10.Resource.Length); Assert.AreEqual(2, allocations.Count); // no new allocation // request another 20-byte array without releasing byte20 = pool.GetOrCreate(20); Assert.AreEqual(20, byte20.Resource.Length); Assert.AreEqual(2, allocations.Count); // no new allocation // allocate another 20-byte array var byte20_2 = pool.GetOrCreate(20); Assert.AreEqual(20, byte20_2.Resource.Length); Assert.AreEqual(3, allocations.Count); // new allocation Assert.AreEqual(20, allocations[2]); // allocate another 10-byte array var byte10_2 = pool.GetOrCreate(10); Assert.AreEqual(10, byte10_2.Resource.Length); Assert.AreEqual(4, allocations.Count); // new allocation Assert.AreEqual(10, allocations[3]); // release all instances byte10.Dispose(); byte20.Dispose(); byte10_2.Dispose(); byte20_2.Dispose(); }
/// <summary> /// Retrieves an image from the pool /// </summary> /// <param name="width">Width of image requested</param> /// <param name="height">Height of image requested</param> /// <param name="pixelFormat">Pixel format for requested image</param> /// <returns>Returns an image frmo the pool</returns> public static Shared <Image> GetOrCreate(int width, int height, PixelFormat pixelFormat) { return(KeyedSharedPool <Image, ValueTuple <long, PixelFormat> > .GetOrCreate(ValueTuple.Create((long)(width * height), pixelFormat), () => Image.Create(width, height, pixelFormat))); }