Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PushGP/HeuristicLab.PushGP/TestPooling/Pool/ManagedPool2.cs @ 14744

Last change on this file since 14744 was 14744, checked in by pkimmesw, 7 years ago

#2665 Renamings due to typos, ManagedPool tests, Skip Noops in Debugger

File size: 2.0 KB
Line 
1using System.Collections.Generic;
2
3namespace TestPooling.Pool {
4  using System;
5  using System.Collections.Concurrent;
6  using System.IO;
7  using System.Linq;
8  using System.Runtime.Serialization.Formatters.Binary;
9
10  public class ManagedPool2<T> : IDisposable where T : class {
11
12    private static readonly ConcurrentStack<T[]> Pool = new ConcurrentStack<T[]>();
13
14    private readonly T[] DummyPartition;
15    private readonly Func<T> Factory;
16    public readonly int PartitionSize;
17
18    private readonly IList<T[]> partitions = new List<T[]>();
19    private T[] currentPartition;
20    private int entryIndex;
21
22    public ManagedPool2(int partitionSize, T[] dummyPartition, Func<T> factory) {
23      PartitionSize = partitionSize;
24      Factory = factory;
25      entryIndex = partitionSize;
26
27      DummyPartition = dummyPartition;
28    }
29
30    public T Get() {
31      if (entryIndex == PartitionSize) {
32        currentPartition = GetPartition();
33        partitions.Add(currentPartition);
34        entryIndex = 0;
35      }
36
37      return currentPartition[entryIndex++];
38    }
39
40    private T[] GetPartition() {
41      //T[] partition;
42
43      //partition = Pool.TryPop(out partition) ? partition : new T[PartitionSize];
44
45      //for (var i = 0; i < PartitionSize; i++) {
46      //  partition[i] = Factory();
47      //}
48
49      //return partition;
50
51      T[] partition;
52      if (Pool.TryPop(out partition)) return partition;
53
54      //partition = new T[PartitionSize];
55      //DummyPartition.CopyTo(partition, 0);
56
57      return DeepArrayCopy(DummyPartition);
58    }
59
60    private static T[] DeepArrayCopy(object objectToCopy) {
61      using (var memoryStream = new MemoryStream()) {
62        var binaryFormatter = new BinaryFormatter();
63
64        binaryFormatter.Serialize(memoryStream, objectToCopy);
65        memoryStream.Seek(0, SeekOrigin.Begin);
66
67        return (T[])binaryFormatter.Deserialize(memoryStream);
68      }
69    }
70
71    public void Dispose() {
72      Pool.PushRange(partitions.ToArray());
73    }
74  }
75}
Note: See TracBrowser for help on using the repository browser.