基本信息
源码名称:C# 夜间自动重启电脑 程序源码(无人看守)
源码大小:0.82M
文件格式:.rar
开发语言:C#
更新时间:2017-11-09
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559

本次赞助数额为: 3 元 
   源码介绍
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.IO;
using System.Configuration;
using System.Threading;
using System.Runtime.InteropServices;

namespace CocoWatcher
{
    public partial class ProcessWatcher : ServiceBase
    {
        private Thread ReStart = null;
        public log4net.ILog log = null;
        private int m_ProcessorCount = 0;       //CPU个数
        private PerformanceCounter pcCpuLoad;   //CPU计数器

        #region API
          [DllImport("IpHlpApi.dll")]
          extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);
  
          [DllImport("User32")]
          private extern static int GetWindow(int hWnd, int wCmd);
  
          [DllImport("User32")]
          private extern static int GetWindowLongA(int hWnd, int wIndx);
  
          [DllImport("user32.dll")]
          private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);
  
          [DllImport("user32", CharSet = CharSet.Auto)]
          private extern static int GetWindowTextLength(IntPtr hWnd);
          #endregion
       


        #region CPU个数
          /// <summary>
          /// 获取CPU个数
          /// </summary>
          public int ProcessorCount
          {
              get
              {
                  return m_ProcessorCount;
              }
          }
          #endregion
  
          #region CPU占用率
          /// <summary>
          /// 获取CPU占用率
          /// </summary>
          public float CpuLoad
          {
              get
              {
                  return pcCpuLoad.NextValue();
              }
          }
          #endregion

        /// <summartstary>
        /// 构造函数
        /// </summary>
        public ProcessWatcher()
        {
            InitializeComponent();
           log = log4net.LogManager.GetLogger(typeof(ProcessWatcher));
        }


        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            try
            {
                string ChangeRegedit = ConfigurationManager.AppSettings["ChangeRegedit"].ToString();
                if (string.Equals(ChangeRegedit, "1"))
                {
                    String oldPath = null;
                    oldPath = Environment.GetEnvironmentVariable("MKL_NUM_THREADS", EnvironmentVariableTarget.Machine);
                    if (oldPath == null)
                    {
                        Environment.SetEnvironmentVariable("MKL_NUM_THREADS", "2", EnvironmentVariableTarget.Machine);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            if (ReStart == null)
            {
                ReStart = new Thread(updateStatuThreadHandle);
                ReStart.IsBackground = true;
                ReStart.Start();
            }
        }

        //public void Start() 
        //{
        //    string[] args=new string[1];
        //    this.OnStart(args);
        //}

        Object lockObject = new Object();
        private void updateStatuThreadHandle(object obj)
        {
            string ProcessName = ConfigurationManager.AppSettings["ProcessName"].ToString();
            string StartTime = ConfigurationManager.AppSettings["StartTime"].ToString();
            string EndTime = ConfigurationManager.AppSettings["EndTime"].ToString();
            int Interval = Int16.Parse(ConfigurationManager.AppSettings["Interval"].ToString());
            log.Info("...........................................探测服务已启动..........................................");
            while (true)
            {
                Thread.Sleep(1000 * 60 * Interval);
                log.Info("...........................................进入探测一次..........................................");
                lock (lockObject)
                {
                    try
                    {
                        string CurrentTime = System.DateTime.Now.ToString("HHmmss");
                        if ((string.Compare(CurrentTime, StartTime) > 0 && string.Compare(EndTime, CurrentTime) > 0) || (string.Compare(CurrentTime, StartTime) == 0))
                        {
                            log.Info("重启时间段内,系统重启--------------------");
                            rebootSystem();
                        }
                        else
                        {
                            Process[] process;//创建一个PROCESS类数组
                            process = Process.GetProcessesByName(ProcessName);//获取当前任务管理器所有运行中程序

                            if (process.Length > 0)
                            {
                                if (process.Length > 1)
                                {
                                    log.Info("存在多个进程--------------------");
                                    rebootSystem();
                                }
                                else
                                {
                                    long memerySize = process[0].PrivateMemorySize64;
                                    Int32 cpu = process[0].ProcessorAffinity.ToInt32();
                                    log.InfoFormat("系统专用内存大小:{0},系统消耗CPU:{1}", memerySize,cpu);
                                    if (memerySize > 850000000 || cpu == 0)
                                    {
                                        log.Info("内存或CPU指标异常------------------");
                                        rebootSystem();
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log.ErrorFormat("监测线程出现异常:{0}", ex);
                        log.Info("...........................................探测服务已停止..........................................");
                    }
                }
                //Thread.Sleep(1000*60*20);
            }
        }


        /// <summary>
        /// 停止服务
        /// </summary>
        protected override void OnStop()
        {
            try
            {
                ReStart.Abort();
                log.Info("...........................................探测服务已停止..........................................");
            }
            catch (Exception ex)
            {
            }
        }

        private void Reboot(Process[] process, string ProcessDirection)
        {
            try
            {
                log.Info("********************进入杀线程入口*************************");
                if (process.Length > 0)
                {
                    foreach (Process proces in process)//遍历
                    {
                        log.Info("进入重新启动,开始杀进程....");
                        proces.Kill();
                    }
                }
                Thread.Sleep(3000);
                log.Info("进入启动进程,....");
                Process p = new Process();
                p.StartInfo.FileName = ProcessDirection;
                //p.StartInfo.UseShellExecute = false;
                //p.StartInfo.WorkingDirectory = ProcessDirection;
                //p.StartInfo.RedirectStandardInput = true;
                //p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.CreateNoWindow = false;
                p.Start();
                //p.StandardInput.WriteLine(@"cd C:\Program Files (x86)\DriverSelfHelp\");
                //p.StandardInput.WriteLine("DriverSelfHelp.exe");
                //Thread.Sleep(30000);
                //p.StandardInput.WriteLine("exit");
            }
            catch (Exception ex) { }
        }

        public void rebootSystem()
        {
            System.Diagnostics.Process.Start("shutdown", @"/r");
        }

        /// <summary>
        /// 开始监控
        /// </summary>
    
             
    }
}