写在前面
有时候我们需要将程序以Windows服务的模式运行,以下是一种非常简单的实现方式。
实现步骤
1.新建一个控制台项目
2.添加App.config,指定服务名称
<configuration>
<appSettings>
<add key="ServiceName" value="MyService" />
</appSettings>
</configuration>
3.主要实现代码
public class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
try
{
var serviceName = ConfigurationManager.AppSettings["ServiceName"];
if (string.IsNullOrEmpty(serviceName))
{
string err = "service name is null";
Console.WriteLine(err);
return;
}
if (args.Count() < 1)
{
Console.WriteLine("Setup Ok");
Console.WriteLine("Start Ok");
}
else if (args.Count() > 0 && args.First() == "--service")
{
ServiceBase.Run(new MyService());
}
else if (args.Count() > 0 && args.First() == "--reg")
{
//by calling the SC program of windows, Administration permission needed.
var arg = string.Format(" create {0} displayname= \"{0}\" binpath= \""
+ Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Assembly.GetEntryAssembly().GetName().Name + ".exe")
+ " --service\"",
serviceName);
var ps = new ProcessStartInfo("sc.exe", arg);
ps.WindowStyle = ProcessWindowStyle.Hidden;
ps.UseShellExecute = false;
var p = Process.Start(ps);
p.WaitForExit();
}//Remove this self from windows services.
else if (args.Count() > 0 && args.First() == "--unreg")
{
var ps = new ProcessStartInfo("sc.exe", string.Format(" delete {0}", serviceName));
ps.WindowStyle = ProcessWindowStyle.Hidden;
ps.UseShellExecute = false;
var p = Process.Start(ps);
p.WaitForExit();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine("Exception:" + e.ExceptionObject.ToString());
}
}
class MyService : ServiceBase
{
public MyService()
{
// 构造器
}
protected override void OnStart(string[] args)
{
try
{
// 调用服务启动时需要执行的方法
base.OnStart(args);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
protected override void OnStop()
{
try
{
// 调用服务停止时需要执行的方法
base.OnStop();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
protected override void OnPause()
{
try
{
// 调用服务暂停时需要执行的方法
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
protected override void OnContinue()
{
try
{
// 调用服务恢复时需要执行的方法
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
验证结果
使用cmd执行,或者做一个批处理;执行RegServiceTest.exe --reg
运行 services.msc 可以查看到服务已经成功创建了。