-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppTaskExecutor.cs
More file actions
76 lines (64 loc) · 2.04 KB
/
AppTaskExecutor.cs
File metadata and controls
76 lines (64 loc) · 2.04 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
namespace AppTask
{
/// <summary>
/// 在此处对系统线程做集中管理
/// </summary>
public class AppTaskExecutor
{
protected static AppTaskExecutor _instance = new AppTaskExecutor();
protected object Sync_Locker = new object();
Dictionary<IAppTask, IAppTaskAsyncResult> _tasks = new Dictionary<IAppTask, IAppTaskAsyncResult>();
public static AppTaskExecutor Singleton
{
get { return _instance; }
}
protected AppTaskExecutor()
{
}
public IAppTaskAsyncResult Execute(IAppTask task)
{
Debug.Assert(task != null);
Thread th = new Thread(task.Run);
th.IsBackground = true;
th.Start();
IAppTaskAsyncResult async_result = new AbstractAppTask.AppTaskAsyncResult(task);
lock (Sync_Locker) {
_tasks.Add(task, async_result);
}
return async_result;
}
public void Stop(IAppTask task)
{
Debug.Assert(task != null);
IAppTaskAsyncResult async_result = null;
lock (Sync_Locker) {
if (_tasks.ContainsKey(task)) {
async_result = _tasks[task];
_tasks.Remove(task);
}
}
if (async_result != null) {
async_result.Interrupt();
async_result.Join();
}
}
public void StopAll()
{
lock (Sync_Locker) {
foreach (IAppTaskAsyncResult async in _tasks.Values) {
async.Interrupt();
}
foreach (IAppTaskAsyncResult async in _tasks.Values) {
async.Join();
}
_tasks.Clear();
}
}
}
}