12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- using System;
- using System.Threading;
- using System.Threading.Tasks;
- namespace Vinno.FIS.Sonopost.Common
- {
- public class ProcessKeepHelper
- {
- private CancellationTokenSource _tokenSource;
- private int _processId;
- public ProcessKeepHelper(int processId)
- {
- _processId = processId;
- }
- /// <summary>
- /// 开起守护进程
- /// </summary>
- /// <param name="restartFunc">重启进程方法,返回进程ID</param>
- public void StartKeepProcess(Func<int> restartFunc)
- {
- if (_tokenSource != null && !_tokenSource.IsCancellationRequested)
- {
- _tokenSource.Cancel();
- }
- _tokenSource = new CancellationTokenSource();
- Task.Run(async () =>
- {
- while (!_tokenSource.IsCancellationRequested)
- {
- var existApp = ProcessHelper.IsProcessExist(_processId);
- if (existApp == null)
- {
- _processId = restartFunc.Invoke();
- }
- await Task.Delay(5000, _tokenSource.Token);
- }
- }, _tokenSource.Token);
- }
- /// <summary>
- /// 开启守护进程
- /// </summary>
- /// <param name="restartFunc"></param>
- public void StartKeepProcess(Func<Task<int>> restartFunc)
- {
- if (_tokenSource != null && !_tokenSource.IsCancellationRequested)
- {
- _tokenSource.Cancel();
- }
- _tokenSource = new CancellationTokenSource();
- Task.Run(async () =>
- {
- while (!_tokenSource.IsCancellationRequested)
- {
- var existApp = ProcessHelper.IsProcessExist(_processId);
- if (existApp == null)
- {
- _processId = await restartFunc.Invoke();
- }
- await Task.Delay(5000, _tokenSource.Token);
- }
- }, _tokenSource.Token);
- }
- /// <summary>
- /// 关闭守护进程
- /// </summary>
- public void StopKeepProcess()
- {
- _tokenSource?.Cancel();
- }
- }
- }
|