/
BackgroundOpStack.cs
106 lines (89 loc) · 2.84 KB
/
BackgroundOpStack.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
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
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows;
namespace Practic.Framework.Support
{
public class BackgroundOpStack
{
private readonly Stack<EncapsulatedAction> _runnableActions = new Stack<EncapsulatedAction>();
private readonly Thread _workerThread;
private volatile bool _isRunning;
public bool IsRunning
{
get { return _isRunning; }
set { _isRunning = value; }
}
private static BackgroundOpStack _instance;
public static BackgroundOpStack Instance
{
get { return _instance ?? (_instance = new BackgroundOpStack()); }
}
private BackgroundOpStack()
{
_workerThread = new Thread(ImYourWorkerBitchYo);
Application.Current.Exit += ShutDown;
_workerThread.Start();
}
private void ShutDown(object sender, EventArgs e)
{
lock (_instance)
{
IsRunning = false;
_runnableActions.Clear();
Monitor.Pulse(_instance);
}
}
public void Enqueue(Action<object> action, object myObj)
{
if (action != null)
lock (_instance)
{
_runnableActions.Push(new EncapsulatedAction(action,myObj));
Monitor.Pulse(_instance);
}
}
private void ImYourWorkerBitchYo()
{
Thread.CurrentThread.Name = "WorkerThread_" + DateTime.Now.ToString("{0:f}");
IsRunning = true;
var privateStack = new Stack<EncapsulatedAction>();
while (IsRunning)
{
lock (_instance)
{
if (_runnableActions.Count > 0)
{
privateStack.Push(_runnableActions.Pop());
}
else
{
Monitor.Wait(_instance);
}
if(!IsRunning)
return;
}
while (privateStack.Count > 0)
{
var op = privateStack.Pop();
op.Run();
Thread.Sleep(0); // OK that yields
}
}
}
private sealed class EncapsulatedAction
{
private readonly Action<object> _action;
private readonly object _state;
public EncapsulatedAction(Action<object> action, object state)
{
_action = action;
_state = state;
}
public void Run()
{
_action(_state);
}
}
}
}