使用.Net Core 2.2创建windows服务
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用.Net Core 2.2创建windows服务,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1690字,纯文字阅读大概需要3分钟。
内容图文
![使用.Net Core 2.2创建windows服务](/upload/InfoBanner/zyjiaocheng/968/f0ec3edff0464698833d7119c98fcd99.jpg)
使用.Net Core 2.2创建windows服务
我的环境
- win 10 home
- Visual Studio 2019 v16.1.3
- 安装有.net core 2.2
创建项目
编辑项目文件
在 PropertyGroup 配置节 加入属性 <RuntimeIdentifier>win-x64</RuntimeIdentifier>
保存后,重新生成项目
在项目文件夹下,会有文件夹 bin\Debug\netcoreapp2.2\win-x64,里面包含了exe文件。
测试服务类的编写
安装nuget包
Install-Package System.ServiceProcess.ServiceController -Version 4.5.0
修改启动类 Programe.cs
using System;
using System.IO;
using System.ServiceProcess;
namespace TestService
{
class Program
{
static void Main(string[] args)
{
using (var service = new TestSevice())
{
ServiceBase.Run(service);
}
}
}
internal class TestSevice : ServiceBase
{
public TestSevice()
{
ServiceName = "TestService";
}
protected override void OnStart(string[] args)
{
string filename = CheckFileExists();
File.AppendAllText(filename, $"{DateTime.Now} started.{Environment.NewLine}");
}
protected override void OnStop()
{
string filename = CheckFileExists();
File.AppendAllText(filename, $"{DateTime.Now} stopped.{Environment.NewLine}");
}
private static string CheckFileExists()
{
string filename = System.AppDomain.CurrentDomain.BaseDirectory + @"\MyService.txt";
if (!File.Exists(filename))
{
File.Create(filename);
}
return filename;
}
}
}
服务安装、启动、卸载
安装
sc create testservice binpath=D:\source\repos\TestConsoleService\TestService\bin\Debug\netcoreapp2.2\win-x64\TestService.exe
卸载
sc delete testservice
启动
不能通过命令行启动服务
sc start testservice
只能去服务管理器使用鼠标启动服务,具体原因暂未研究
反复启动停止,然后去exe所在目录下查看MyService.txt的内容,确认服务的启动。
参考文档
- Running a .NET Core Generic Host App as a Windows Service
- Create windows service using .Net Core (Console application)
内容总结
以上是互联网集市为您收集整理的使用.Net Core 2.2创建windows服务全部内容,希望文章能够帮你解决使用.Net Core 2.2创建windows服务所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。