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.
 
 

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