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.
 
 

154 lines
5.7 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. namespace HBLConsole.Service
  10. {
  11. /// <summary>
  12. /// 线程管理
  13. /// </summary>
  14. public class ThreadOperate
  15. {
  16. private volatile static ThreadOperate _Instance;
  17. public static ThreadOperate GetInstance => _Instance ?? (_Instance = new ThreadOperate());
  18. private ThreadOperate() { }
  19. string guid = "871d7e28-c413-4675-8d28-64e4dca4c2d3-";
  20. ConcurrentDictionary<string, Task> Threads = new ConcurrentDictionary<string, Task>();
  21. ConcurrentDictionary<string, CancellationTokenSource> CancellationTokenSources = new ConcurrentDictionary<string, CancellationTokenSource>();
  22. /// <summary>
  23. /// 停止指定任务
  24. /// </summary>
  25. /// <param name="taskName">任务名</param>
  26. /// <param name="ExitCallback">任务结束的回调</param>
  27. public void StopTask(string taskName, Action ExitCallback = null)
  28. {
  29. if (CancellationTokenSources.ContainsKey(guid + taskName))
  30. CancellationTokenSources[guid + taskName]?.Cancel();
  31. ActionOperate.GetInstance.Register(ExitCallback, guid + taskName);
  32. }
  33. /// <summary>
  34. /// 长任务,带 while true 的循环
  35. /// </summary>
  36. /// <param name="action"></param>
  37. /// <param name="TaskName"></param>
  38. public void StartLong(Action action, string TaskName, Action RunComplete = null)
  39. {
  40. CancellationTokenSources.TryAdd(guid + TaskName, new CancellationTokenSource());
  41. bool result = Threads.TryAdd(guid + TaskName, Task.Factory.StartNew(new Action(() =>
  42. {
  43. try
  44. {
  45. while (!CancellationTokenSources[guid + TaskName].IsCancellationRequested)
  46. {
  47. if (action != null) action();
  48. }
  49. }
  50. catch (Exception ex)
  51. {
  52. MessageLog.GetInstance.Show($"线程 【{TaskName}】运行发生异常,已重启");
  53. CancellationTokenSources.TryRemove(guid + TaskName, out CancellationTokenSource temp);
  54. Threads.TryRemove(guid + TaskName, out Task temp1);
  55. }
  56. }), CancellationTokenSources[guid + TaskName].Token).ContinueWith(new Action<Task, object>((t, o) =>
  57. {
  58. ThreadStatus(t, o.ToString());
  59. if (RunComplete != null) RunComplete();
  60. }), guid + TaskName));
  61. MessageLog.GetInstance.Show($"启动线程 【{TaskName}】");
  62. if (!result) MessageLog.GetInstance.Show($"【{TaskName}】任务已存在,请检查 TaskName");
  63. }
  64. /// <summary>
  65. /// 不带 while true 的循环任务
  66. /// </summary>
  67. /// <param name="action"></param>
  68. /// <param name="TaskName"></param>
  69. public void Start(Action action, string TaskName)
  70. {
  71. CancellationTokenSources.TryAdd(guid + TaskName, new CancellationTokenSource());
  72. bool result = Threads.TryAdd(guid + TaskName, Task.Factory.StartNew(new Action(() =>
  73. {
  74. action();
  75. }), CancellationTokenSources[guid + TaskName].Token).ContinueWith(new Action<Task, object>((t, o) =>
  76. {
  77. ThreadStatus(t, o.ToString());
  78. }), guid + TaskName));
  79. if (!result) MessageLog.GetInstance.Show($"【{TaskName}】任务已存在,请检查 TaskName");
  80. }
  81. private void ThreadStatus(Task task, string TaskName)
  82. {
  83. bool IsRemove = false;
  84. string name = TaskName.Substring(TaskName.LastIndexOf('-') + 1);
  85. switch (task.Status)
  86. {
  87. case TaskStatus.RanToCompletion:
  88. MessageLog.GetInstance.Show($"线程【{name}】执行完成");
  89. IsRemove = true;
  90. break;
  91. case TaskStatus.Faulted:
  92. MessageLog.GetInstance.Show($"线程【{name}】执行异常,{task.Exception}");
  93. IsRemove = true;
  94. break;
  95. case TaskStatus.Canceled:
  96. MessageLog.GetInstance.Show($"线程【{name}】已取消");
  97. IsRemove = true;
  98. break;
  99. default:
  100. break;
  101. }
  102. if (IsRemove)
  103. {
  104. if (Threads.ContainsKey(TaskName))
  105. Threads.TryRemove(Threads.FirstOrDefault(p => p.Key == TaskName));
  106. if (CancellationTokenSources.ContainsKey(TaskName))
  107. CancellationTokenSources.TryRemove(CancellationTokenSources.FirstOrDefault(p => p.Key == TaskName));
  108. ActionOperate.GetInstance.Send(TaskName);
  109. }
  110. }
  111. /// <summary>
  112. /// 释放所有线程资源
  113. /// </summary>
  114. public void Dispose()
  115. {
  116. for (int i = 0; i < CancellationTokenSources.Count; i++)
  117. {
  118. CancellationTokenSources.ElementAt(i).Value.Cancel();
  119. }
  120. }
  121. /// <summary>
  122. /// 判断指定线程是否完成
  123. /// </summary>
  124. /// <param name="TaskName"></param>
  125. /// <returns></returns>
  126. public bool IsComplete(string TaskName)
  127. {
  128. if (Threads.ContainsKey(guid + TaskName))
  129. {
  130. return Threads[guid + TaskName].IsCompleted;
  131. }
  132. else
  133. {
  134. return false;
  135. }
  136. }
  137. }
  138. }