终端一体化运控平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

194 lines
7.5 KiB

  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. if (key.Equals("MainTask"))
  34. {
  35. ActionManage.GetInstance.Send("FryPotDosingMainTaskExit");
  36. }
  37. ActionManage.GetInstance.Register(ExitCallback, guid + key);
  38. }
  39. else
  40. {
  41. if (ExitCallback != null) ExitCallback();
  42. }
  43. }
  44. /// <summary>
  45. /// 长任务,带 while true 的循环
  46. /// </summary>
  47. /// <param name="action"></param>
  48. /// <param name="key"></param>
  49. public void StartLong(Action action, string key, bool IsRestart = false, Action RunComplete = null)
  50. {
  51. CancellationTokenSources.TryAdd(guid + key, new CancellationTokenSource());
  52. bool result = Threads.TryAdd(guid + key, Task.Factory.StartNew(new Action(() =>
  53. {
  54. Thread.CurrentThread.Name = key;
  55. ReStart:
  56. try
  57. {
  58. while (!CancellationTokenSources[guid + key].IsCancellationRequested)
  59. {
  60. if (action != null) action();
  61. }
  62. }
  63. catch (Exception ex)
  64. {
  65. MessageLog.GetInstance.ShowEx(ex.ToString());
  66. if (IsRestart)
  67. {
  68. Thread.Sleep(2000);
  69. MessageLog.GetInstance.Show($"线程 【{key}】运行发生异常,已重启");
  70. goto ReStart;
  71. }
  72. else
  73. {
  74. CancellationTokenSources.TryRemove(guid + key, out CancellationTokenSource temp);
  75. Threads.TryRemove(guid + key, out Task temp1);
  76. MessageLog.GetInstance.Show($"线程 【{key}】运行发生异常,已退出");
  77. }
  78. }
  79. }), CancellationTokenSources[guid + key].Token).ContinueWith(new Action<Task, object>((t, o) =>
  80. {
  81. ThreadStatus(t, o.ToString());
  82. if (RunComplete != null) RunComplete();
  83. }), guid + key));
  84. MessageLog.GetInstance.Show($"启动线程 【{key}】");
  85. if (!result) MessageLog.GetInstance.Show($"【{key}】任务已存在,请检查 TaskName");
  86. }
  87. /// <summary>
  88. /// 不带 while true 的循环任务
  89. /// </summary>
  90. /// <param name="action"></param>
  91. /// <param name="key"></param>
  92. public void Start(Action action, string key, bool isRestart = false)
  93. {
  94. CancellationTokenSources.TryAdd(guid + key, new CancellationTokenSource());
  95. bool result = Threads.TryAdd(guid + key, Task.Factory.StartNew(new Action(() =>
  96. {
  97. Thread.CurrentThread.Name = key;
  98. try
  99. {
  100. if (action != null) action();
  101. }
  102. catch (Exception ex)
  103. {
  104. MessageLog.GetInstance.ShowEx(ex.ToString());
  105. if (isRestart)
  106. {
  107. MessageLog.GetInstance.Show($"线程 【{key}】正在重启");
  108. CancellationTokenSources.TryRemove(guid + key, out CancellationTokenSource item1);
  109. Threads.TryRemove(guid + key, out Task item2);
  110. Start(action, key, isRestart);
  111. }
  112. else
  113. {
  114. MessageLog.GetInstance.Show($"线程 【{key}】运行发生异常");
  115. }
  116. }
  117. }), CancellationTokenSources[guid + key].Token).ContinueWith(new Action<Task, object>((t, o) =>
  118. {
  119. ThreadStatus(t, o.ToString());
  120. }), guid + key));
  121. MessageLog.GetInstance.Show($"启动线程 【{key}】");
  122. if (!result) MessageLog.GetInstance.Show($"【{key}】任务已存在,请检查 TaskName");
  123. }
  124. private void ThreadStatus(Task task, string key)
  125. {
  126. bool IsRemove = false;
  127. string name = key.Substring(key.LastIndexOf('-') + 1);
  128. switch (task.Status)
  129. {
  130. case TaskStatus.RanToCompletion:
  131. MessageLog.GetInstance.Show($"线程【{name}】执行完成");
  132. IsRemove = true;
  133. break;
  134. case TaskStatus.Faulted:
  135. MessageLog.GetInstance.Show($"线程【{name}】执行异常,{task.Exception}");
  136. IsRemove = true;
  137. break;
  138. case TaskStatus.Canceled:
  139. MessageLog.GetInstance.Show($"线程【{name}】已取消");
  140. IsRemove = true;
  141. break;
  142. default:
  143. break;
  144. }
  145. if (IsRemove)
  146. {
  147. if (Threads.ContainsKey(key))
  148. Threads.TryRemove(key, out Task t);
  149. //Threads.TryRemove(Threads.FirstOrDefault(p => p.Key == TaskName));
  150. if (CancellationTokenSources.ContainsKey(key))
  151. CancellationTokenSources.TryRemove(key, out CancellationTokenSource cts);
  152. //CancellationTokenSources.TryRemove(CancellationTokenSources.FirstOrDefault(p => p.Key == TaskName));
  153. //keys.Remove(key);
  154. //if (keys != null && keys.Count == 0) ActionManage.GetInstance.Send(callbackKey.ToString());
  155. ActionManage.GetInstance.Send(key);
  156. }
  157. }
  158. /// <summary>
  159. /// 释放所有线程资源
  160. /// </summary>
  161. public void Dispose()
  162. {
  163. for (int i = 0; i < CancellationTokenSources.Count; i++)
  164. {
  165. CancellationTokenSources.ElementAt(i).Value.Cancel();
  166. }
  167. }
  168. /// <summary>
  169. /// 判断指定线程是否完成
  170. /// </summary>
  171. /// <param name="key"></param>
  172. /// <returns></returns>
  173. public bool IsComplete(string key)
  174. {
  175. if (Threads.ContainsKey(guid + key)) return Threads[guid + key].IsCompleted;
  176. return false;
  177. }
  178. }
  179. }