终端一体化运控平台
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

ThreadManage.cs 7.3 KiB

2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Collections.Concurrent;
  7. using System.Diagnostics;
  8. using System.Threading;
  9. using BPASmartClient.Message;
  10. namespace BPASmartClient.Helper
  11. {
  12. /// <summary>
  13. /// 线程管理
  14. /// </summary>
  15. public class ThreadManage : Singleton<ThreadManage>
  16. {
  17. string guid = "871d7e28-c413-4675-8d28-64e4dca4c2d3-";
  18. private static readonly object _lock = new object();
  19. StringBuilder callbackKey = new StringBuilder();
  20. List<string> keys = new List<string>();
  21. ConcurrentDictionary<string, Task> Threads = new ConcurrentDictionary<string, Task>();
  22. ConcurrentDictionary<string, CancellationTokenSource> CancellationTokenSources = new ConcurrentDictionary<string, CancellationTokenSource>();
  23. /// <summary>
  24. /// 停止指定任务
  25. /// </summary>
  26. /// <param name="key">任务名</param>
  27. /// <param name="ExitCallback">任务结束的回调</param>
  28. public void StopTask(string key, Action ExitCallback = null)
  29. {
  30. if (CancellationTokenSources.ContainsKey(guid + key))
  31. {
  32. CancellationTokenSources[guid + key]?.Cancel();
  33. ActionManage.GetInstance.Register(ExitCallback, guid + key);
  34. }
  35. else
  36. {
  37. if (ExitCallback != null) ExitCallback();
  38. }
  39. }
  40. /// <summary>
  41. /// 长任务,带 while true 的循环
  42. /// </summary>
  43. /// <param name="action"></param>
  44. /// <param name="key"></param>
  45. public void StartLong(Action action, string key, bool IsRestart = false, Action RunComplete = null)
  46. {
  47. CancellationTokenSources.TryAdd(guid + key, new CancellationTokenSource());
  48. bool result = Threads.TryAdd(guid + key, Task.Factory.StartNew(new Action(() =>
  49. {
  50. Thread.CurrentThread.Name = key;
  51. ReStart:
  52. try
  53. {
  54. while (!CancellationTokenSources[guid + key].IsCancellationRequested)
  55. {
  56. if (action != null) action();
  57. }
  58. }
  59. catch (Exception ex)
  60. {
  61. MessageLog.GetInstance.ShowEx(ex.ToString());
  62. if (IsRestart)
  63. {
  64. Thread.Sleep(2000);
  65. MessageLog.GetInstance.Show($"线程 【{key}】运行发生异常,已重启");
  66. goto ReStart;
  67. }
  68. else
  69. {
  70. CancellationTokenSources.TryRemove(guid + key, out CancellationTokenSource temp);
  71. Threads.TryRemove(guid + key, out Task temp1);
  72. MessageLog.GetInstance.Show($"线程 【{key}】运行发生异常,已退出");
  73. }
  74. }
  75. }), CancellationTokenSources[guid + key].Token).ContinueWith(new Action<Task, object>((t, o) =>
  76. {
  77. ThreadStatus(t, o.ToString());
  78. if (RunComplete != null) RunComplete();
  79. }), guid + key));
  80. MessageLog.GetInstance.Show($"启动线程 【{key}】");
  81. if (!result) MessageLog.GetInstance.Show($"【{key}】任务已存在,请检查 TaskName");
  82. }
  83. /// <summary>
  84. /// 不带 while true 的循环任务
  85. /// </summary>
  86. /// <param name="action"></param>
  87. /// <param name="key"></param>
  88. public void Start(Action action, string key, bool isRestart = false)
  89. {
  90. CancellationTokenSources.TryAdd(guid + key, new CancellationTokenSource());
  91. bool result = Threads.TryAdd(guid + key, Task.Factory.StartNew(new Action(() =>
  92. {
  93. Thread.CurrentThread.Name = key;
  94. try
  95. {
  96. if (action != null) action();
  97. }
  98. catch (Exception ex)
  99. {
  100. MessageLog.GetInstance.ShowEx(ex.ToString());
  101. if (isRestart)
  102. {
  103. MessageLog.GetInstance.Show($"线程 【{key}】正在重启");
  104. CancellationTokenSources.TryRemove(guid + key, out CancellationTokenSource item1);
  105. Threads.TryRemove(guid + key, out Task item2);
  106. Start(action, key, isRestart);
  107. }
  108. else
  109. {
  110. MessageLog.GetInstance.Show($"线程 【{key}】运行发生异常");
  111. }
  112. }
  113. }), CancellationTokenSources[guid + key].Token).ContinueWith(new Action<Task, object>((t, o) =>
  114. {
  115. ThreadStatus(t, o.ToString());
  116. }), guid + key));
  117. MessageLog.GetInstance.Show($"启动线程 【{key}】");
  118. if (!result) MessageLog.GetInstance.Show($"【{key}】任务已存在,请检查 TaskName");
  119. }
  120. private void ThreadStatus(Task task, string key)
  121. {
  122. bool IsRemove = false;
  123. string name = key.Substring(key.LastIndexOf('-') + 1);
  124. switch (task.Status)
  125. {
  126. case TaskStatus.RanToCompletion:
  127. MessageLog.GetInstance.Show($"线程【{name}】执行完成");
  128. IsRemove = true;
  129. break;
  130. case TaskStatus.Faulted:
  131. MessageLog.GetInstance.Show($"线程【{name}】执行异常,{task.Exception}");
  132. IsRemove = true;
  133. break;
  134. case TaskStatus.Canceled:
  135. MessageLog.GetInstance.Show($"线程【{name}】已取消");
  136. IsRemove = true;
  137. break;
  138. default:
  139. break;
  140. }
  141. if (IsRemove)
  142. {
  143. if (Threads.ContainsKey(key))
  144. Threads.TryRemove(key, out Task t);
  145. //Threads.TryRemove(Threads.FirstOrDefault(p => p.Key == TaskName));
  146. if (CancellationTokenSources.ContainsKey(key))
  147. CancellationTokenSources.TryRemove(key, out CancellationTokenSource cts);
  148. //CancellationTokenSources.TryRemove(CancellationTokenSources.FirstOrDefault(p => p.Key == TaskName));
  149. //keys.Remove(key);
  150. //if (keys != null && keys.Count == 0) ActionManage.GetInstance.Send(callbackKey.ToString());
  151. ActionManage.GetInstance.Send(key);
  152. }
  153. }
  154. /// <summary>
  155. /// 释放所有线程资源
  156. /// </summary>
  157. public void Dispose()
  158. {
  159. for (int i = 0; i < CancellationTokenSources.Count; i++)
  160. {
  161. CancellationTokenSources.ElementAt(i).Value.Cancel();
  162. }
  163. }
  164. /// <summary>
  165. /// 判断指定线程是否完成
  166. /// </summary>
  167. /// <param name="key"></param>
  168. /// <returns></returns>
  169. public bool IsComplete(string key)
  170. {
  171. if (Threads.ContainsKey(guid + key)) return Threads[guid + key].IsCompleted;
  172. return false;
  173. }
  174. }
  175. }