forked from laicasaane/unity-supplements
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray1ConcurrentPool{T}.cs
More file actions
95 lines (77 loc) · 2.29 KB
/
Copy pathArray1ConcurrentPool{T}.cs
File metadata and controls
95 lines (77 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace System.Collections.Pooling.Concurrent
{
public static class Array1ConcurrentPool<T>
{
private static readonly PoolMap _poolMap = new PoolMap();
public static T[] Get(int size)
=> Get((long)size);
public static T[] Get(long size)
{
if (size < 0)
throw new ArgumentOutOfRangeException(nameof(size), "Must be a positive number.");
if (_poolMap.TryGetValue(size, out var pool))
{
if (pool.TryDequeue(out var item))
return item;
}
else
{
_poolMap.TryAdd(size, new ConcurrentQueue<T[]>());
}
return new T[size];
}
public static void Return(T[] item)
{
if (item == null)
return;
item.Clear();
Return(item.LongLength, item);
}
public static void Return(params T[][] items)
{
if (items == null)
return;
foreach (var item in items)
{
if (item == null)
continue;
item.Clear();
Return(item.LongLength, item);
}
}
public static void Return(IEnumerable<T[]> items)
{
if (items == null)
return;
foreach (var item in items)
{
if (item == null)
continue;
item.Clear();
Return(item.LongLength, item);
}
}
private static void Return(long size, T[] item)
{
if (!_poolMap.TryGetValue(size, out var pool))
{
_poolMap.TryAdd(size, pool = new ConcurrentQueue<T[]>());
}
pool.Enqueue(item);
}
public static void Clear()
{
foreach (var kv in _poolMap)
{
while (kv.Value.Count > 0)
{
kv.Value.TryDequeue(out _);
}
}
_poolMap.Clear();
}
private class PoolMap : ConcurrentDictionary<long, ConcurrentQueue<T[]>> { }
}
}