使用TopShelf做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(); }
    }

 

posted @ 2017-07-28 09:56  以沫浅夏  阅读(273)  评论(0编辑  收藏  举报