forked from Taritsyn/JavaScriptEngineSwitcher
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScriptDispatcher.cs
More file actions
302 lines (260 loc) · 6.53 KB
/
ScriptDispatcher.cs
File metadata and controls
302 lines (260 loc) · 6.53 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
using System;
using System.Collections.Generic;
#if NETSTANDARD1_3 || NET45
using System.Runtime.ExceptionServices;
#endif
using System.Threading;
using JavaScriptEngineSwitcher.Core;
using JavaScriptEngineSwitcher.Core.Utilities;
namespace JavaScriptEngineSwitcher.ChakraCore
{
/// <summary>
/// Provides services for managing the queue of script tasks on the thread with increased stack size
/// </summary>
internal sealed class ScriptDispatcher : IDisposable
{
#if !NETSTANDARD1_3
/// <summary>
/// The stack size is sufficient to run the code of modern JavaScript libraries in 32-bit process
/// </summary>
const int STACK_SIZE_32 = 492 * 1024; // like 32-bit Node.js
/// <summary>
/// The stack size is sufficient to run the code of modern JavaScript libraries in 64-bit process
/// </summary>
const int STACK_SIZE_64 = 984 * 1024; // like 64-bit Node.js
#endif
/// <summary>
/// The thread with increased stack size
/// </summary>
private Thread _thread;
/// <summary>
/// Event to signal when the new script task entered to the queue
/// </summary>
private AutoResetEvent _waitHandle = new AutoResetEvent(false);
/// <summary>
/// Queue of script tasks
/// </summary>
private readonly Queue<ScriptTask> _taskQueue = new Queue<ScriptTask>();
/// <summary>
/// Synchronizer of script task queue
/// </summary>
private readonly object _taskQueueSynchronizer = new object();
/// <summary>
/// Flag that object is destroyed
/// </summary>
private InterlockedStatedFlag _disposedFlag = new InterlockedStatedFlag();
/// <summary>
/// Constructs an instance of script dispatcher
/// </summary>
public ScriptDispatcher()
{
#if NETSTANDARD1_3
_thread = new Thread(StartThread)
#else
int sufficientStackSize = Utils.Is64BitProcess() ? STACK_SIZE_64 : STACK_SIZE_32;
_thread = new Thread(StartThread, sufficientStackSize)
#endif
{
IsBackground = true
};
_thread.Start();
}
private void VerifyNotDisposed()
{
if (_disposedFlag.IsSet())
{
throw new ObjectDisposedException(ToString());
}
}
/// <summary>
/// Starts a thread with increased stack size.
/// Loops forever, processing script tasks from the queue.
/// </summary>
private void StartThread()
{
while(true)
{
ScriptTask task = null;
lock (_taskQueueSynchronizer)
{
if (_taskQueue.Count > 0)
{
task = _taskQueue.Dequeue();
if (task == null)
{
_taskQueue.Clear();
return;
}
}
}
if (task != null)
{
try
{
task.Result = task.Delegate();
}
catch (Exception e)
{
task.Exception = e;
}
task.WaitHandle.Set();
}
else
{
_waitHandle.WaitOne();
}
}
}
/// <summary>
/// Adds a script task to the end of the queue
/// </summary>
/// <param name="task">Script task</param>
private void EnqueueTask(ScriptTask task)
{
lock (_taskQueueSynchronizer)
{
_taskQueue.Enqueue(task);
}
_waitHandle.Set();
}
/// <summary>
/// Runs a specified delegate on the thread with increased stack size,
/// and returns its result as an <see cref="System.Object"/>.
/// Blocks until the invocation of delegate is completed.
/// </summary>
/// <param name="del">Delegate to invocation</param>
/// <returns>Result of the delegate invocation</returns>
private object InnnerInvoke(Func<object> del)
{
ScriptTask task;
using (var waitHandle = new ManualResetEvent(false))
{
task = new ScriptTask(del, waitHandle);
EnqueueTask(task);
waitHandle.WaitOne();
}
Exception exception = task.Exception;
if (exception != null)
{
#if NETSTANDARD1_3 || NET45
ExceptionDispatchInfo.Capture(exception).Throw();
#elif NET40
exception.PreserveStackTrace();
throw exception;
#else
#error No implementation for this target
#endif
}
return task.Result;
}
/// <summary>
/// Runs a specified delegate on the thread with increased stack size,
/// and returns its result as an <typeparamref name="T" />.
/// Blocks until the invocation of delegate is completed.
/// </summary>
/// <typeparam name="T">The type of the return value of the method,
/// that specified delegate encapsulates</typeparam>
/// <param name="func">Delegate to invocation</param>
/// <returns>Result of the delegate invocation</returns>
public T Invoke<T>(Func<T> func)
{
VerifyNotDisposed();
if (func == null)
{
throw new ArgumentNullException("func");
}
return (T)InnnerInvoke(() => func());
}
/// <summary>
/// Runs a specified delegate on the thread with increased stack size.
/// Blocks until the invocation of delegate is completed.
/// </summary>
/// <param name="action">Delegate to invocation</param>
public void Invoke(Action action)
{
VerifyNotDisposed();
if (action == null)
{
throw new ArgumentNullException("action");
}
InnnerInvoke(() =>
{
action();
return null;
});
}
#region IDisposable implementation
/// <summary>
/// Destroys object
/// </summary>
public void Dispose()
{
if (_disposedFlag.Set())
{
EnqueueTask(null);
if (_thread != null)
{
_thread.Join();
_thread = null;
}
if (_waitHandle != null)
{
_waitHandle.Dispose();
_waitHandle = null;
}
}
}
#endregion
#region Internal types
/// <summary>
/// Represents a script task, that must be executed on separate thread
/// </summary>
private sealed class ScriptTask
{
/// <summary>
/// Gets a delegate to invocation
/// </summary>
public Func<object> Delegate
{
get;
private set;
}
/// <summary>
/// Gets a event to signal when the invocation of delegate has completed
/// </summary>
public ManualResetEvent WaitHandle
{
get;
private set;
}
/// <summary>
/// Gets or sets a result of the delegate invocation
/// </summary>
public object Result
{
get;
set;
}
/// <summary>
/// Gets or sets a exception, that occurred during the invocation of delegate.
/// If no exception has occurred, this will be null.
/// </summary>
public Exception Exception
{
get;
set;
}
/// <summary>
/// Constructs an instance of script task
/// </summary>
/// <param name="del">Delegate to invocation</param>
/// <param name="waitHandle">Event to signal when the invocation of delegate has completed</param>
public ScriptTask(Func<object> del, ManualResetEvent waitHandle)
{
Delegate = del;
WaitHandle = waitHandle;
}
}
#endregion
}
}