您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

446 行
15 KiB

  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace HKCardIN.Helper
  9. {
  10. public class Singleton<T> where T : new()
  11. {
  12. private static object _async = new object();
  13. private static T _instance;
  14. static readonly Lazy<T> instance = new();
  15. /// <summary>
  16. /// 获取实例
  17. /// </summary>
  18. /// <returns></returns>
  19. public static T GetInstance()
  20. {
  21. return instance.Value;
  22. }
  23. }
  24. public class ThreadManage : Singleton<ThreadManage>
  25. {
  26. string guid = "871d7e28-c413-4675-8d28-64e4dca4c2d3-";
  27. private static readonly object _lock = new object();
  28. StringBuilder callbackKey = new StringBuilder();
  29. List<string> keys = new List<string>();
  30. ConcurrentDictionary<string, Task> Threads = new ConcurrentDictionary<string, Task>();
  31. ConcurrentDictionary<string, CancellationTokenSource> CancellationTokenSources = new ConcurrentDictionary<string, CancellationTokenSource>();
  32. /// <summary>
  33. /// 停止指定任务
  34. /// </summary>
  35. /// <param name="key">任务名</param>
  36. /// <param name="ExitCallback">任务结束的回调</param>
  37. public void StopTask(string key, Action ExitCallback = null)
  38. {
  39. if (CancellationTokenSources.ContainsKey(guid + key))
  40. {
  41. CancellationTokenSources[guid + key]?.Cancel();
  42. ActionManage.GetInstance.Register(ExitCallback, guid + key);
  43. }
  44. else
  45. {
  46. if (ExitCallback != null) ExitCallback();
  47. }
  48. }
  49. /// <summary>
  50. /// 长任务,带 while true 的循环
  51. /// </summary>
  52. /// <param name="action"></param>
  53. /// <param name="key"></param>
  54. public void StartLong(Action action, string key, bool IsRestart = false, Action RunComplete = null)
  55. {
  56. CancellationTokenSources.TryAdd(guid + key, new CancellationTokenSource());
  57. bool result = Threads.TryAdd(guid + key, Task.Factory.StartNew(new Action(() =>
  58. {
  59. Thread.CurrentThread.Name = key;
  60. ReStart:
  61. try
  62. {
  63. while (!CancellationTokenSources[guid + key].IsCancellationRequested)
  64. {
  65. if (action != null) action();
  66. }
  67. }
  68. catch (Exception ex)
  69. {
  70. if (IsRestart)
  71. {
  72. Thread.Sleep(2000);
  73. goto ReStart;
  74. }
  75. else
  76. {
  77. CancellationTokenSources.TryRemove(guid + key, out CancellationTokenSource temp);
  78. Threads.TryRemove(guid + key, out Task temp1);
  79. }
  80. }
  81. }), CancellationTokenSources[guid + key].Token).ContinueWith(new Action<Task, object>((t, o) =>
  82. {
  83. ThreadStatus(t, o.ToString());
  84. if (RunComplete != null) RunComplete();
  85. }), guid + key));
  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. if (isRestart)
  105. {
  106. CancellationTokenSources.TryRemove(guid + key, out CancellationTokenSource item1);
  107. Threads.TryRemove(guid + key, out Task item2);
  108. Start(action, key, isRestart);
  109. }
  110. else
  111. {
  112. }
  113. }
  114. }), CancellationTokenSources[guid + key].Token).ContinueWith(new Action<Task, object>((t, o) =>
  115. {
  116. ThreadStatus(t, o.ToString());
  117. }), guid + key));
  118. }
  119. private void ThreadStatus(Task task, string key)
  120. {
  121. bool IsRemove = false;
  122. string name = key.Substring(key.LastIndexOf('-') + 1);
  123. switch (task.Status)
  124. {
  125. case TaskStatus.RanToCompletion:
  126. IsRemove = true;
  127. break;
  128. case TaskStatus.Faulted:
  129. IsRemove = true;
  130. break;
  131. case TaskStatus.Canceled:
  132. IsRemove = true;
  133. break;
  134. default:
  135. break;
  136. }
  137. if (IsRemove)
  138. {
  139. if (Threads.ContainsKey(key))
  140. Threads.TryRemove(key, out Task t);
  141. if (CancellationTokenSources.ContainsKey(key))
  142. CancellationTokenSources.TryRemove(key, out CancellationTokenSource cts);
  143. ActionManage.GetInstance.Send(key);
  144. }
  145. }
  146. /// <summary>
  147. /// 释放所有线程资源
  148. /// </summary>
  149. public void Dispose()
  150. {
  151. for (int i = 0; i < CancellationTokenSources.Count; i++)
  152. {
  153. CancellationTokenSources.ElementAt(i).Value.Cancel();
  154. }
  155. }
  156. /// <summary>
  157. /// 判断指定线程是否完成
  158. /// </summary>
  159. /// <param name="key"></param>
  160. /// <returns></returns>
  161. public bool IsComplete(string key)
  162. {
  163. if (Threads.ContainsKey(guid + key)) return Threads[guid + key].IsCompleted;
  164. return false;
  165. }
  166. }
  167. internal class Delegation
  168. {
  169. /// <summary>
  170. /// 带参数的委托
  171. /// </summary>
  172. public Action<object> ActionPar { get; set; }
  173. /// <summary>
  174. /// 带参数的委托
  175. /// </summary>
  176. public Action<object[]> ActionPars { get; set; }
  177. /// <summary>
  178. /// 无参数的委托
  179. /// </summary>
  180. public Action ActionBus { get; set; }
  181. /// <summary>
  182. /// 有返回值的委托
  183. /// </summary>
  184. public Func<object> FuncObj { get; set; }
  185. /// <summary>
  186. /// 有返回值,有参数的委托
  187. /// </summary>
  188. public Func<object, object> FuncPar { get; set; }
  189. }
  190. public class ActionManage
  191. {
  192. private volatile static ActionManage _Instance;
  193. public static ActionManage GetInstance => _Instance ?? (_Instance = new ActionManage());
  194. private ActionManage() { }
  195. //private static ConcurrentDictionary<string, delegate> actions = new ConcurrentDictionary<string, delegate>();
  196. private static ConcurrentDictionary<string, Delegation> actions = new ConcurrentDictionary<string, Delegation>();
  197. static readonly object SendLock = new object();
  198. static readonly object SendParLock = new object();
  199. static readonly object RegisterLock = new object();
  200. /// <summary>
  201. /// 注销委托
  202. /// </summary>
  203. /// <param name="key"></param>
  204. public void CancelRegister(string key)
  205. {
  206. if (actions.ContainsKey(key))
  207. actions.TryRemove(key, out Delegation t);
  208. }
  209. /// <summary>
  210. /// 执行注册过的委托
  211. /// </summary>
  212. /// <param name="key">注册委托的key</param>
  213. /// <param name="par">委托参数</param>
  214. /// <param name="Callback">委托回调</param>
  215. public void Send(string key, object par, Action Callback = null)
  216. {
  217. lock (SendLock)
  218. if (actions.ContainsKey(key)) actions[key].ActionPar.Invoke(par, Callback);
  219. }
  220. /// <summary>
  221. /// 执行注册过的委托
  222. /// </summary>
  223. /// <param name="key">注册委托的key</param>
  224. /// <param name="par">委托参数</param>
  225. /// <param name="Callback">委托回调</param>
  226. public void Send(string key, object[] par, Action Callback = null)
  227. {
  228. lock (SendLock)
  229. if (actions.ContainsKey(key)) actions[key].ActionPars.Invokes(par, Callback);
  230. }
  231. /// <summary>
  232. /// 执行注册过的委托
  233. /// </summary>
  234. /// <param name="key">注册委托的key</param>
  235. /// <param name="Callback">委托回调</param>
  236. public void Send(string key, Action Callback = null)
  237. {
  238. lock (SendLock)
  239. if (actions.ContainsKey(key)) actions[key].ActionBus?.Invoke(Callback);
  240. }
  241. public object SendResult(string key, object par = null)
  242. {
  243. lock (SendLock)
  244. if (actions.ContainsKey(key))
  245. if (par == null)
  246. {
  247. return actions[key].FuncObj?.Invoke();
  248. }
  249. else
  250. {
  251. return actions[key].FuncPar?.Invoke(par);
  252. }
  253. return default;
  254. }
  255. public void Register<T>(T action, string key)
  256. {
  257. lock (RegisterLock)
  258. {
  259. if (action != null)
  260. {
  261. if (!actions.ContainsKey(key))
  262. {
  263. if (action is Action actionBus)
  264. actions.TryAdd(key, new Delegation() { ActionBus = actionBus });
  265. if (action is Action<object> actionObj)
  266. actions.TryAdd(key, new Delegation() { ActionPar = actionObj });
  267. if (action is Action<object[]> actionObjs)
  268. actions.TryAdd(key, new Delegation() { ActionPars = actionObjs });
  269. if (action is Func<object> funcObj)
  270. actions.TryAdd(key, new Delegation() { FuncObj = funcObj });
  271. if (action is Func<object, object> puncPar)
  272. actions.TryAdd(key, new Delegation() { FuncPar = puncPar });
  273. }
  274. }
  275. }
  276. }
  277. }
  278. public static class ExpandMethod
  279. {
  280. /// <summary>
  281. /// 获取布尔数组指定值得索引
  282. /// </summary>
  283. /// <param name="obj">要获取索引的数组</param>
  284. /// <param name="value">要获取索引的值</param>
  285. /// <returns></returns>
  286. public static int GetIndex(this bool[] obj, bool value)
  287. {
  288. if (obj == null) return -1;
  289. return Array.FindIndex(obj, p => p == value);
  290. }
  291. /// <summary>
  292. /// 获取字符串数组指定值得索引
  293. /// </summary>
  294. /// <param name="obj">要获取索引的数组</param>
  295. /// <param name="value">要获取索引的值</param>
  296. /// <returns></returns>
  297. public static int GetIndex(this string[] obj, string value)
  298. {
  299. if (obj == null || value == null) return -1;
  300. return Array.FindIndex(obj, p => p == value && p.Length > 0);
  301. }
  302. /// <summary>
  303. /// 委托回调
  304. /// </summary>
  305. /// <param name="action">要执行的委托</param>
  306. /// <param name="callback">委托回调</param>
  307. public static void Invoke(this Action action, Action callback)
  308. {
  309. action?.Invoke();
  310. callback?.Invoke();
  311. }
  312. /// <summary>
  313. /// 委托回调
  314. /// </summary>
  315. /// <param name="action">要执行的委托</param>
  316. /// <param name="par">要执行的委托的参数</param>
  317. /// <param name="callback">委托回调</param>
  318. public static void Invoke(this Action<object> action, object par, Action callback)
  319. {
  320. action?.Invoke(par);
  321. callback?.Invoke();
  322. }
  323. public static void Invokes(this Action<object[]> action, object[] par, Action callback)
  324. {
  325. action?.Invoke(par);
  326. callback?.Invoke();
  327. }
  328. /// <summary>
  329. /// 字节数组转换成32位整数
  330. /// </summary>
  331. /// <param name="bytes"></param>
  332. /// <returns></returns>
  333. public static int BytesToInt(this byte[] bytes)
  334. {
  335. if (bytes.Length > 4) return -1;
  336. int ReturnVlaue = 0;
  337. for (int i = 0; i < bytes.Length; i++)
  338. {
  339. ReturnVlaue += (int)(bytes[i] << (i * 8));
  340. }
  341. return ReturnVlaue;
  342. }
  343. /// <summary>
  344. /// 字节数组转换成 ushort 数组
  345. /// </summary>
  346. /// <param name="bytes">要转换的字节数组</param>
  347. /// <param name="reverse">字节高度顺序控制</param>
  348. /// <returns></returns>
  349. public static ushort[] BytesToUshorts(this byte[] bytes, bool reverse = false)
  350. {
  351. int len = bytes.Length;
  352. byte[] srcPlus = new byte[len + 1];
  353. bytes.CopyTo(srcPlus, 0);
  354. int count = len >> 1;
  355. if (len % 2 != 0)
  356. {
  357. count += 1;
  358. }
  359. ushort[] dest = new ushort[count];
  360. if (reverse)
  361. {
  362. for (int i = 0; i < count; i++)
  363. {
  364. dest[i] = (ushort)(srcPlus[i * 2] << 8 | srcPlus[2 * i + 1] & 0xff);
  365. }
  366. }
  367. else
  368. {
  369. for (int i = 0; i < count; i++)
  370. {
  371. dest[i] = (ushort)(srcPlus[i * 2] & 0xff | srcPlus[2 * i + 1] << 8);
  372. }
  373. }
  374. return dest;
  375. }
  376. /// <summary>
  377. /// ushort 数组转换成字节数组
  378. /// </summary>
  379. /// <param name="src">需要转换的 ushort数组</param>
  380. /// <param name="reverse">高低字节的设置</param>
  381. /// <returns></returns>
  382. public static byte[] UshortsToBytes(this ushort[] src, bool reverse = false)
  383. {
  384. int count = src.Length;
  385. byte[] dest = new byte[count << 1];
  386. if (reverse)
  387. {
  388. for (int i = 0; i < count; i++)
  389. {
  390. dest[i * 2] = (byte)(src[i] >> 8);
  391. dest[i * 2 + 1] = (byte)(src[i] >> 0);
  392. }
  393. }
  394. else
  395. {
  396. for (int i = 0; i < count; i++)
  397. {
  398. dest[i * 2] = (byte)(src[i] >> 0);
  399. dest[i * 2 + 1] = (byte)(src[i] >> 8);
  400. }
  401. }
  402. return dest;
  403. }
  404. }
  405. }