--近期有一个需要运用多线程的项目,会有并发概率,所以写了一份代码,可能有写地方还不完善,后续有需求在改
1 /// <summary>
2 /// 并发对象
3 /// </summary>
4 public class MeterAsyncQueue
5 {
6 public MeterAsyncQueue()
7 {
8 MeterInfoTask = new MeterInfo();
9 }
10
11 public MeterInfo MeterInfoTask { get; set; }
12 }
13 public class MeterInfo
14 {
15 public MeterInfo()
16 {
17
18 }
19 public int Id { get; set; }
20
21 }
1 /// <summary>
2 /// 线程通用类
3 /// </summary>
4 public class TaskCommand
5 {
6 CancellationTokenSource tokenSource = new CancellationTokenSource();
7 ManualResetEvent resetEvent = new ManualResetEvent(true);
8 Thread thread = null;
9 /// <summary>
10 /// 开始任务
11 /// </summary>
12 public void StartData()
13 {
14 tokenSource = new CancellationTokenSource();
15 resetEvent = new ManualResetEvent(true);
16
17 List<int> Ids = new List<int>();
18 for (int i = 0; i < 10000; i++)
19 {
20 Ids.Add(i);
21 }
22 thread = new Thread(new ThreadStart(() => StartTask(Ids)));
23 thread.Start();
24 }
25 /// <summary>
26 /// 暂停任务
27 /// </summary>
28 public void OutData()
29 {
30 //task暂停
31 resetEvent.Reset();
32 }
33 /// <summary>
34 /// 继续任务
35 /// </summary>
36 public void ContinueData()
37 {
38 //task继续
39 resetEvent.Set();
40 }
41 /// <summary>
42 /// 取消任务
43 /// </summary>
44 public void Cancel()
45 {
46 //释放对象
47 resetEvent.Dispose();
48 foreach (var CurrentTask in ParallelTasks)
49 {
50 if (CurrentTask != null)
51 {
52 if (CurrentTask.Status == TaskStatus.Running) { }
53 {
54 //终止task线程
55 tokenSource.Cancel();
56 }
57 }
58 }
59 thread.Abort();
60 }
61 /// <summary>
62 /// 执行数据
63 /// </summary>
64 /// <param name="Index"></param>
65 public void Execute(int Index)
66 {
67 //阻止当前线程
68 resetEvent.WaitOne();
69
70 Console.WriteLine("当前第" + Index + "个线程");
71
72 Thread.Sleep(1000);
73
74 }
75 //队列对象
76 private Queue<MeterAsyncQueue> AsyncQueues { get; set; }
77
78 /// <summary>
79 /// 并发任务数
80 /// </summary>
81 private int ParallelTaskCount { get; set; }
82
83
84 /// <summary>
85 /// 并行任务集合
86