C# 监控windows服务,针对因异常停止的服务进行重启

十年河东,十年河西,莫欺少年穷

学无止境,精益求精

在部署windows服务后,如果服务偶尔因系统异常停止工作,短期时间内无法找到解决方案,那么只能采用亡羊补牢的办法了,如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace BatteryStartServices
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }
        System.Timers.Timer timer1;  //计时器
        List<string> services = new List<string>() { "BatteryCabinetService", "BatteryOtaService", "BatteryService" };
        protected override void OnStart(string[] args)
        {
            timer1 = new System.Timers.Timer();
            timer1.Interval = 10000;  //设置计时器事件间隔执行时间  每隔10秒执行一次
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
            timer1.Enabled = true;
        }

        protected override void OnStop()
        {
            timer1.Enabled = false;
        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            foreach(var item in services)
            {
                ServiceController service = new ServiceController(item);
                try
                {
                    if (service.Status != ServiceControllerStatus.Running)
                    {
                        service.Start();
                        service.WaitForStatus(ServiceControllerStatus.Running);

                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
           
        }
    }
}

除了以上程序外,我们还需要将exe文件设置为以管理员运行,如下:

 

 这样就有权限重启其他服务了。

@天才卧龙的波尔克

 

posted @ 2021-03-22 11:00  天才卧龙  阅读(1019)  评论(0编辑  收藏  举报