-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathThreadBase.cs
146 lines (124 loc) · 3.72 KB
/
ThreadBase.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
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
using System;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Text;
using System.Threading;
namespace DigitalPlatform.Core
{
/// <summary>
/// 线程基础类
/// </summary>
// [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class ThreadBase : IDisposable
{
private volatile bool m_bStopThread = true;
protected Thread _thread = null;
public AutoResetEvent eventClose = new AutoResetEvent(false); // true : initial state is signaled
public AutoResetEvent eventActive = new AutoResetEvent(false); // 激活信号
public int PerTime = 1000; // 1 秒 5 * 60 * 1000; // 5 分钟
#if NO
public virtual void Clear()
{
}
#endif
public virtual void Dispose()
{
eventActive.Dispose();
eventClose.Dispose();
}
void ThreadMain()
{
m_bStopThread = false;
try
{
WaitHandle[] events = new WaitHandle[2];
events[0] = eventClose;
events[1] = eventActive;
while (m_bStopThread == false)
{
int index = 0;
try
{
index = WaitHandle.WaitAny(events, PerTime, false);
}
catch (System.Threading.ThreadAbortException /*ex*/)
{
break;
}
if (index == WaitHandle.WaitTimeout)
{
// 超时
eventActive.Reset();
Worker();
// eventActive.Reset(); // 这一句会造成 Worker 中的 Activate 无效
}
else if (index == 0)
{
break;
}
else
{
// 得到激活信号
eventActive.Reset();
Worker();
// eventActive.Reset(); // 这一句会造成 Worker 中的 Activate 无效
}
}
return;
}
finally
{
m_bStopThread = true;
this._thread = null;
}
}
public virtual void Worker()
{
}
public bool Stopped
{
get
{
return m_bStopThread;
}
set
{
m_bStopThread = value;
}
}
public virtual void StopThread(bool bForce)
{
if (this._thread == null)
return;
// 如果以前在做,立即停止
// this.Clear();
m_bStopThread = true;
this.eventClose.Set();
if (bForce == true)
{
if (this._thread != null)
{
if (!this._thread.Join(2000))
this._thread.Abort();
this._thread = null;
}
}
}
public void BeginThread()
{
if (this._thread != null)
return;
// 如果以前在做,立即停止
StopThread(true);
this.eventActive.Set();
this.eventClose.Reset();
this._thread = new Thread(new ThreadStart(this.ThreadMain));
this._thread.Start();
}
public void Activate()
{
eventActive.Set();
}
}
}