C#如何编写Windows服务
起因
这两天在写一个定时任务,在一个Windows服务项目中. 便想着在.Net Core是不是可以编写Windows服务,果真是可以的.1. 在.Net Framework中可以用installutil服务进行注册和卸载
--注册服务
C:/Windows/Microsoft.NET/Framework/v4.0.30319/installutil -i E:/project/csharp/dotnetcore31/dotnet.core/qiufeng.service2/bin/Debug/qiufeng.service2.exe
--卸载服务
C:/Windows/Microsoft.NET/Framework/v4.0.30319/installutil /u E:/project/csharp/dotnetcore31/dotnet.core/qiufeng.service2/bin/Debug/qiufeng.service2.exe
--启动服务
net start Service1
--关闭服务
net stop Service1
2. 创建.Net Core控制台程序
在Nuget中,查找 System.ServiceProcess.ServiceController 进行安装.然后添加新项
namespace CoreService
{
partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// TODO: 在此处添加代码以启动服务。
}
protected override void OnStop()
{
// TODO: 在此处添加代码以执行停止服务所需的关闭操作。
}
}
}
static void Main(string[] args)
{
ServiceBase[] services = new ServiceBase[]
{
new Service1() //可以增加多个服务
};
ServiceBase.Run(services);
}
3. .Net Core的windows服务注册和卸载
在.Net Core中没有installutil工具.该怎么注册服务呢?#使用管理员权限打开命令行工具,用powershell不可以,目前没发现哪里的问题
#sc create xxx(服务名称) binpath=xxx(服务所在的绝对路径) 注册服务
sc create qiufengservice binpath=xxx
#sc delete xxx(服务名称) 卸载服务
#sc delete qiufengservice
在后面.Net版本有新的用法,不过本质上还是在ServiceBase基础上封装.后面可以专门写一篇.
秋风
2020-09-01