.net6使用Topshelf

发布时间 2023-07-04 17:33:59作者: elegydance
using Topshelf;
using TopShelf6Test;

Console.WriteLine("Hello, World!");
HostFactory.Run(x =>
{
    x.Service<MyService>(s =>
    {
        s.ConstructUsing(name => new MyService());
        s.WhenStarted(tc => tc.Start());
        s.WhenStopped(tc => tc.Stop());
    });
    x.RunAsLocalSystem();
    x.StartAutomatically();
    x.SetServiceName("MyService");
    x.SetDisplayName("My Service");
    x.SetDescription("This is my service.");
});


using Topshelf;
using Topshelf.Logging;
using Yells.Common.IO;

namespace TopShelf6Test
{ 
    public class MyService
    {
        public void Start()
        {
            // 在这里实现服务启动逻辑
            Console.WriteLine("start");
            Console.WriteLine(DateTime.Now);

            LogWrite.Info(DateTime.Now.ToString() + " MyService start");
        }

        public void Stop()
        {
            Console.WriteLine("stop");
            Console.WriteLine(DateTime.Now);
            LogWrite.Info(DateTime.Now.ToString() + " MyService stop");
            // 在这里实现服务停止逻辑
        }
    }
}

   

 

只需nuget引用Topshelf 4.3.0