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:
1.5 KB
|
Line | |
---|
1 | using System.Collections.Generic;
|
---|
2 |
|
---|
3 | namespace TestPooling.Pool {
|
---|
4 | using System;
|
---|
5 | using System.Collections.Concurrent;
|
---|
6 | using System.Linq;
|
---|
7 |
|
---|
8 | public class ManagedPool<T> : IDisposable where T : class {
|
---|
9 |
|
---|
10 | private static readonly ConcurrentStack<LinkedList<T>> Pool = new ConcurrentStack<LinkedList<T>>();
|
---|
11 | private readonly Func<T> Factory;
|
---|
12 | public readonly int PartitionSize;
|
---|
13 |
|
---|
14 | private readonly IList<LinkedList<T>> partitions = new List<LinkedList<T>>();
|
---|
15 | private LinkedList<T> currentPartition;
|
---|
16 | private LinkedListNode<T> currentNode;
|
---|
17 |
|
---|
18 | private int entryIndex = 0;
|
---|
19 |
|
---|
20 | public ManagedPool(int partitionSize, Func<T> factory) {
|
---|
21 | PartitionSize = partitionSize;
|
---|
22 | Factory = factory;
|
---|
23 | }
|
---|
24 |
|
---|
25 | public T Get() {
|
---|
26 | if (currentPartition == null || entryIndex == PartitionSize) {
|
---|
27 | currentPartition = GetPartition();
|
---|
28 | currentNode = currentPartition.First;
|
---|
29 | entryIndex = 0;
|
---|
30 |
|
---|
31 | partitions.Add(currentPartition);
|
---|
32 | }
|
---|
33 |
|
---|
34 | T entry;
|
---|
35 | if (currentNode == null) {
|
---|
36 | entry = Factory();
|
---|
37 | currentPartition.AddLast(entry);
|
---|
38 | } else {
|
---|
39 | entry = currentNode.Value;
|
---|
40 | currentNode = currentNode.Next;
|
---|
41 | }
|
---|
42 |
|
---|
43 | entryIndex++;
|
---|
44 |
|
---|
45 | return entry;
|
---|
46 | }
|
---|
47 |
|
---|
48 | private LinkedList<T> GetPartition() {
|
---|
49 | LinkedList<T> partition;
|
---|
50 |
|
---|
51 | return Pool.TryPop(out partition) ? partition : new LinkedList<T>();
|
---|
52 | }
|
---|
53 |
|
---|
54 | public void Dispose() {
|
---|
55 | Pool.PushRange(partitions.ToArray());
|
---|
56 | }
|
---|
57 | }
|
---|
58 | }
|
---|
Note: See
TracBrowser
for help on using the repository browser.