Repository navigation
Expand file tree
/
Copy pathThreadWorker.cs
More file actions
63 lines (58 loc) · 1.94 KB
/
Copy pathThreadWorker.cs
File metadata and controls
63 lines (58 loc) · 1.94 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
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
using System.Diagnostics;
namespace System.Threading.Internal
{
internal class ThreadWorker
{
Thread thread;
WaitCallback callback;
object state;
internal bool IsFree => thread == null || callback == null || thread.ThreadState == ThreadState.Suspended;
internal int Id => thread != null ? thread.ManagedThreadId : -1;
internal SynchronizationContext SynchronizationContext { get; private set; }
AutoResetEvent run = new AutoResetEvent(false);
void Start()
{
thread = new Thread(() =>
{
while (true)
{
Debug.WriteLine($"Thread {Id} started");
try
{
callback(state);
callback = null;
state = null;
}
catch { }
ThreadPool.RunPendingWorkItems(this);
//if more job was posted to this pool as a result of call to RunPendingWorkItems, continue the work immediately
if (callback != null)
continue;
Debug.WriteLine($"Thread {Id} exited");
run.WaitOne();
}
});
SynchronizationContext = new NanoFrameworkSynchronizationContext(thread.ManagedThreadId);
thread.Start();
}
public void Post(WaitCallback callback, object state)
{
this.state = state;
this.callback = callback;
if (thread == null)
{
Start();
}
else
{
run.Set();
}
}
}
}