forked from yuzd/ClearScript.Manager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathManagerPool.cs
More file actions
93 lines (80 loc) · 3.06 KB
/
ManagerPool.cs
File metadata and controls
93 lines (80 loc) · 3.06 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
using System;
using System.Collections.Concurrent;
namespace JavaScript.Manager
{
/// <summary>
/// Defines a pool from which Runtime Managers are requested.
/// </summary>
public interface IManagerPool
{
/// <summary>
/// Gets a runtime from the pool. Blocks until a manager becomes available.
/// </summary>
/// <returns>The next available IRuntimeManager.</returns>
IRuntimeManager GetRuntime();
/// <summary>
/// Returns a Runtime Manager to the pool.
/// </summary>
/// <param name="runtimeManager">The Runtime Manager to return to the pool.</param>
void ReturnToPool(IRuntimeManager runtimeManager);
}
/// <summary>
/// Defines a pool from which Runtime Managers are requested.
/// </summary>
public class ManagerPool : IManagerPool
{
/// <summary>
/// Static reference to the current pool of Runtime Managers.
/// </summary>
public static IManagerPool CurrentPool;
private readonly object _addLock = new object();
/// <summary>
/// Current count of Runtimes within the pool.
/// </summary>
public int RuntimeCurrentCount = 0;
private readonly BlockingCollection<IRuntimeManager> _availableRuntimes = new BlockingCollection<IRuntimeManager>();
private readonly IManagerSettings _settings;
/// <summary>
/// Creates a new Runtime Manager Pool.
/// </summary>
/// <param name="settings">Settings to apply to the Runtime Manager.</param>
public ManagerPool(IManagerSettings settings)
{
if(settings == null)
throw new ArgumentNullException("settings", "Settings must be supplied to the RuntimePool.");
_settings = settings;
}
/// <summary>
/// Initializes the CurrentPool with the provided settings.
/// </summary>
/// <param name="settings">Settings to apply.</param>
public static void InitializeCurrentPool(IManagerSettings settings)
{
CurrentPool = new ManagerPool(settings);
}
public IRuntimeManager GetRuntime()
{
IRuntimeManager manager;
if (_availableRuntimes.TryTake(out manager))
return manager;
int runtimeMaxCount = _settings.RuntimeMaxCount;
if (RuntimeCurrentCount < runtimeMaxCount)
{
lock (_addLock)
{
if (RuntimeCurrentCount < runtimeMaxCount)
{
var runtime = new RuntimeManager(_settings);
RuntimeCurrentCount++;
return runtime;
}
}
}
return _availableRuntimes.Take();
}
public void ReturnToPool(IRuntimeManager runtimeManager)
{
_availableRuntimes.Add(runtimeManager);
}
}
}