使用Topshelf创建Windows服务
2021-04-13 08:28
阅读:594
Topshelf是一个开源的跨平台的服务框架,支持Windows和Mono,只需要几行代码就可以构建一个很方便使用的服务. 官方网站:http://topshelf-project.com
下面是将普通控制台创建成Windows服务:
1.引用程序集TopShelf.dll
通过NuGet安装或者官网下载
2.创建ApiMain类

public class APIMain
{
public APIMain()
{
//初始化方法,可以不要
}
public void Start()
{
//服务启动,执行的内容
}
public void Stop()
{
//服务停止,执行的内容
}
}

3.改写Program.cs

public class Program
{
static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.Service(s =>
{
s.ConstructUsing(name => new APIMain());
s.WhenStarted(tc => tc.Start()); //启动服务执行方法
s.WhenStopped(tc => tc.Stop()); //停止服务前执行方法
});
x.RunAsLocalSystem();
x.SetDescription("数据接口服务"); //服务描述名称
x.SetDisplayName("数据接口服务"); //服务显示名称
x.SetServiceName("ElegantWebApiServer");
});
}
}

4.cmd命令安装或卸载服务
安装:xxx.exe install
卸载:xxx.exe uninstall
文章来自:搜素材网的编程语言模块,转载请注明文章出处。
文章标题:使用Topshelf创建Windows服务
文章链接:http://soscw.com/index.php/essay/75119.html
文章标题:使用Topshelf创建Windows服务
文章链接:http://soscw.com/index.php/essay/75119.html
评论
亲,登录后才可以留言!