-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPool{T}.cs
55 lines (44 loc) · 1.19 KB
/
Pool{T}.cs
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
using System.Collections.Generic;
namespace System.Collections.Pooling
{
public class Pool<T> : IPool<T> where T : class, new()
{
private readonly Queue<T> pool = new Queue<T>();
public void Prepool(int count)
{
for (var i = 0; i < count; i++)
{
this.pool.Enqueue(new T());
}
}
public T Get()
=> this.pool.Count > 0 ? this.pool.Dequeue() : new T();
public void Return(T item)
{
if (item == null || this.pool.Contains(item))
return;
this.pool.Enqueue(item);
}
public void Return(params T[] items)
{
if (items == null)
return;
foreach (var item in items)
{
Return(item);
}
}
public void Return(IEnumerable<T> items)
{
if (items == null)
return;
foreach (var item in items)
{
Return(item);
}
}
public void Clear()
=> this.pool.Clear();
public static Pool<T> Default { get; } = new Pool<T>();
}
}