-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPool.cs
More file actions
83 lines (75 loc) · 2.63 KB
/
Copy pathPool.cs
File metadata and controls
83 lines (75 loc) · 2.63 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
namespace Engine
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Implements a pool of recyclable resources.
/// </summary>
/// <typeparam name="T">The object type.</typeparam>
public class Pool<T>
where T : new()
{
/// <summary>
/// Stores the internal object instance reserve.
/// </summary>
private readonly Queue<T> pool;
/// <summary>
/// Keeps track of the withdrawn objects.
/// </summary>
private readonly HashSet<T> borrowedItems;
/// <summary>
/// Initializes a new instance of the <see cref="Pool{T}"/> class.
/// </summary>
/// <param name="capacity">The capacity.</param>
/// <exception cref="ArgumentException">The <paramref name="capacity"/> must be greater than zero.</exception>
public Pool(int capacity)
{
if (capacity <= 0)
{
throw new ArgumentException($"{nameof(capacity)} must be greater than zero", nameof(capacity));
}
this.pool = new Queue<T>(capacity);
this.borrowedItems = new HashSet<T>(capacity);
foreach (var _ in Enumerable.Range(1, capacity))
{
this.pool.Enqueue(new T());
}
}
/// <summary>
/// Gets a value indicating whether the pool has any items left for withdrawal.
/// </summary>
public bool CanWithdraw => this.pool.Count > 0;
/// <summary>
/// Pulls a free item from the pool.
/// </summary>
/// <returns>The item.</returns>
/// <exception cref="InvalidOperationException">The pool is exhausted.</exception>
public T Withdraw()
{
if (!this.CanWithdraw)
{
throw new InvalidOperationException("The pool is exhausted.");
}
var availableItem = this.pool.Dequeue();
this.borrowedItems.Add(availableItem);
return availableItem;
}
/// <summary>
/// Returns the specified item back to the pool.
/// </summary>
/// <param name="item">The item.</param>
/// <exception cref="InvalidOperationException">The returned item did not belong to the pool.</exception>
public void Return(T item)
{
if (this.borrowedItems.Remove(item))
{
this.pool.Enqueue(item);
}
else
{
throw new InvalidOperationException("The returned item did not belong to the pool.");
}
}
}
}