ProcessKeepHelper.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace Vinno.FIS.Sonopost.Common
  5. {
  6. public class ProcessKeepHelper
  7. {
  8. private CancellationTokenSource _tokenSource;
  9. private int _processId;
  10. public ProcessKeepHelper(int processId)
  11. {
  12. _processId = processId;
  13. }
  14. /// <summary>
  15. /// 开起守护进程
  16. /// </summary>
  17. /// <param name="restartFunc">重启进程方法,返回进程ID</param>
  18. public void StartKeepProcess(Func<int> restartFunc)
  19. {
  20. if (_tokenSource != null && !_tokenSource.IsCancellationRequested)
  21. {
  22. _tokenSource.Cancel();
  23. }
  24. _tokenSource = new CancellationTokenSource();
  25. Task.Run(async () =>
  26. {
  27. while (!_tokenSource.IsCancellationRequested)
  28. {
  29. var existApp = ProcessHelper.IsProcessExist(_processId);
  30. if (existApp == null)
  31. {
  32. _processId = restartFunc.Invoke();
  33. }
  34. await Task.Delay(5000, _tokenSource.Token);
  35. }
  36. }, _tokenSource.Token);
  37. }
  38. /// <summary>
  39. /// 开启守护进程
  40. /// </summary>
  41. /// <param name="restartFunc"></param>
  42. public void StartKeepProcess(Func<Task<int>> restartFunc)
  43. {
  44. if (_tokenSource != null && !_tokenSource.IsCancellationRequested)
  45. {
  46. _tokenSource.Cancel();
  47. }
  48. _tokenSource = new CancellationTokenSource();
  49. Task.Run(async () =>
  50. {
  51. while (!_tokenSource.IsCancellationRequested)
  52. {
  53. var existApp = ProcessHelper.IsProcessExist(_processId);
  54. if (existApp == null)
  55. {
  56. _processId = await restartFunc.Invoke();
  57. }
  58. await Task.Delay(5000, _tokenSource.Token);
  59. }
  60. }, _tokenSource.Token);
  61. }
  62. /// <summary>
  63. /// 关闭守护进程
  64. /// </summary>
  65. public void StopKeepProcess()
  66. {
  67. _tokenSource?.Cancel();
  68. }
  69. }
  70. }