使用TopShelf做windows服务

本文介绍了一个使用C#编写的简单服务程序示例,该程序能够以本地系统身份运行,并通过一个名为TownCrier的类实现定时打印当前时间的功能。此示例展示了如何创建并注册Windows服务,以及如何定义和服务相关的生命周期方法。
  class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>                                 //1
            {
                x.RunAsLocalSystem();                            //6
                x.StartAutomatically();
                x.SetDescription("服务测试");        //7
                x.SetDisplayName("服务测试1");                       //8
                x.SetServiceName("服务测试名称");                       //9

                x.Service<TownCrier>(s =>                        //2
                {
                    s.ConstructUsing(name => new TownCrier());     //3
                    s.WhenStarted(tc => tc.Start());              //4
                    s.WhenStopped(tc => tc.Stop());               //5
                });
            });
        }
    }

    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(); }
    }

 

转载于:https://www.cnblogs.com/liyangLife/p/7248648.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值