forked from stevenh/HttpServer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObjectPool.cs
59 lines (53 loc) · 1.82 KB
/
ObjectPool.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
56
57
58
59
using System;
using System.Collections.Generic;
namespace HttpServer.Tools
{
/// <summary>
/// Flyweight design pattern implementation.
/// </summary>
/// <typeparam name="T">Type of object.</typeparam>
public class ObjectPool<T> where T : class
{
private readonly CreateHandler<T> _createMethod;
private readonly Queue<T> _items = new Queue<T>();
/// <summary>
/// Initializes a new instance of the <see cref="ObjectPool{T}"/> class.
/// </summary>
/// <param name="createHandler">How large buffers to allocate.</param>
public ObjectPool(CreateHandler<T> createHandler)
{
_createMethod = createHandler;
}
/// <summary>
/// Get an object.
/// </summary>
/// <returns>Created object.</returns>
/// <remarks>Will create one if queue is empty.</remarks>
public T Dequeue()
{
lock (_items)
{
if (_items.Count > 0)
return _items.Dequeue();
}
return _createMethod();
}
/// <summary>
/// Enqueues the specified buffer.
/// </summary>
/// <param name="value">Object to enqueue.</param>
/// <exception cref="ArgumentOutOfRangeException">Buffer is is less than the minimum requirement.</exception>
public void Enqueue(T value)
{
lock (_items)
_items.Enqueue(value);
}
}
/// <summary>
/// Used to create new objects.
/// </summary>
/// <typeparam name="T">Type of objects to create.</typeparam>
/// <returns>Newly created object.</returns>
/// <seealso cref="ObjectPool{T}"/>.
public delegate T CreateHandler<T>() where T : class;
}