美文网首页
Topshelf创建Windows Service

Topshelf创建Windows Service

作者: 寻找无名的特质 | 来源:发表于2021-12-16 06:00 被阅读0次

开源项目TopSelf提供了创建Windows Service的简单易用方法。项目网站:Topshelf (topshelf-project.com)
项目的代码可以从github下载:Topshelf/Topshelf: An easy service hosting framework for building Windows services using .NET (github.com)
使用非常简单,创建一个控制台程序,引用Nuget包Topshelf和Topshelf.log4net,官网的示例代码如下:

public class TownCrier
{
    readonly Timer _timer;
    public TownCrier()
    {
        _timer = new Timer(1000) {AutoReset = true};
        _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now);
    }
    public void Start() { _timer.Start(); }
    public void Stop() { _timer.Stop(); }
}

public class Program
{
    public static void Main()
    {
        var rc = HostFactory.Run(x =>                                   //1
        {
            x.Service<TownCrier>(s =>                                   //2
            {
               s.ConstructUsing(name=> new TownCrier());                //3
               s.WhenStarted(tc => tc.Start());                         //4
               s.WhenStopped(tc => tc.Stop());                          //5
            });
            x.RunAsLocalSystem();                                       //6

            x.SetDescription("Sample Topshelf Host");                   //7
            x.SetDisplayName("Stuff");                                  //8
            x.SetServiceName("Stuff");                                  //9
        });                                                             //10

        var exitCode = (int) Convert.ChangeType(rc, rc.GetTypeCode());  //11
        Environment.ExitCode = exitCode;
    }
}

主要使用使用HostFactory.Run方法注册服务。代码很容易懂。安装服务、启动服务和停止服务都很简单:
安装:TopshelfDemo.exe install
启动:TopshelfDemo.exe start
卸载:TopshelfDemo.exe uninstall

相关文章

网友评论

      本文标题:Topshelf创建Windows Service

      本文链接:https://www.haomeiwen.com/subject/mydjfrtx.html