C# 应用ServiceController控制自定义windows service
在C#中,windows service专案编译部署后,可以通过ServiceController在外部对此Windows service加以控制:可以停止,可以重新启动等,也可以传递特定的指令给windows service,
windows service接收到这些指令后,可以根据定义做些特定的事情。
using System; using System.ServiceProcess; using System.Text; using System.IO; namespace myScheduledJob { public partial class ScheduledJob : ServiceBase { public ScheduledJob() { InitializeComponent(); } protected override void OnStart(string[] args) { writeLog("windows service Started at " + DateTime.Now.ToString()); } protected override void OnStop() { writeLog("windows service Stoped at " + DateTime.Now.ToString()); } /// <summary> /// 此方法用于接收特定的Command /// </summary> /// <param name="command">command指令</param> protected override void OnCustomeCommand(int command) { if (command >= 128 && command <= 255) { switch (command) { case 140: { writeLog("windows service received command" + command); } break; case 141: { writeLog("windows service received command" + command); } break; } } else { writeLog("service command is invalid"); } } private void writeLog(string text) { Monitor.Enter(lockObject); System.IO.StreamWriter sw = null; try { string logPath = systemPath + @"\" + logForderPath; string logFile = logPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt"; string fullText = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\t" + text; checkFile(logFile); sw = System.IO.File.AppendText(logFile); sw.WriteLine(fullText); sw.Flush(); sw.Close(); } finally { Monitor.Exit(lockObject); } } private void checkFile(string fileName) { if (!System.IO.File.Exists(fileName)) { System.IO.StreamWriter sw = System.IO.File.CreateText(fileName); sw.Close(); } } } }
需要注意的是:Command指令接收的参数限制:int, 128-255.
接下来通过如下测试代码演示上述内容:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Reflection; using System.Threading; using System.ServiceProcess; namespace fileSystemWatcherDemo { class Program { static void Main(string[] args) { Command(); } private static void Command() { Console.WriteLine("Please input the command:"); string cmd = Console.ReadLine(); Console.WriteLine("You have Input the " + cmd); if (cmd != "q") { sendCommandToService(cmd); Command(); } } private static void sendCommandToService(string cmd) { try { ServiceController sc = new ServiceController(); sc.MachineName = Environment.MachineName; sc.ServiceName = "myScheduledJob"; sc.ExecuteCommand(Convert.ToInt32(cmd)); //使用此命令,Service必须是Started 状态,cmd必须是128-255之间整数 } catch (Exception ex) { Console.WriteLine(ex.InnerException); } //利用ServiceController可以控制Windows Service
//if (sc.Status == ServiceControllerStatus.Stopped) // sc.Start(); //else // sc.Stop(); } } }