forked from ahotko/c-sharp-code-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObjectPoolSample.cs
65 lines (57 loc) · 1.6 KB
/
ObjectPoolSample.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
60
61
62
63
64
65
using System;
using System.Collections.Concurrent;
namespace CodeSamples.UsefulClasses
{
#region ObjectPool Class
public class ObjectPool<T>
{
private ConcurrentBag<T> _objects;
private Func<T> _objectGenerator;
public ObjectPool(Func<T> objectGenerator)
{
if (objectGenerator == null) throw new ArgumentNullException("objectGenerator");
_objects = new ConcurrentBag<T>();
_objectGenerator = objectGenerator;
}
public T GetObject()
{
T item;
if (_objects.TryTake(out item)) return item;
return _objectGenerator();
}
public void PutObject(T item)
{
_objects.Add(item);
}
}
#endregion
#region Worker Class
public class MyWorkerClass
{
public MyWorkerClass()
{
Console.WriteLine("Generated worker...");
}
public void DoSomething()
{
Console.WriteLine("...done something");
}
}
#endregion
public class ObjectPoolSample: SampleExecute
{
private ObjectPool<MyWorkerClass> _pool = new ObjectPool<MyWorkerClass>(() => new MyWorkerClass());
public override void Execute()
{
Title($"ObjectPoolExecute");
for(int i = 0; i < 5; i++)
{
//only 1 worker class will be created and then reused
var worker = _pool.GetObject();
worker.DoSomething();
_pool.PutObject(worker);
}
Finish();
}
}
}