Windows service

昨天部署一个自己写的windows service,在服务器上一直无法启动,启动的过程需要很长时间,然后直接被停止,后来查看了一下代码,发现在service的OnStart里面是这样写的

         protected override void OnStart(string[] args)

        {
            monitor = new WebSiteMonitor();
            monitor.StartMonitor();            
        } 

其中WebSiteMonitor.StartMonitor()里面有取网站信息并访问,获取状态的操作,这是一个相对比较耗时的工作——问题就是出在这了 

解决方案: 这儿可以另起一个线程来启动这个监控程序 

          protected override void OnStart(string[] args)

        {
            WebSiteMonitor monitor = new WebSiteMonitor();
            _thread = new Thread(new ThreadStart(monitor.StartMonitor));
            _thread.Start();
        }

这样的话这个耗时的操作是在另一个线程里执行的,服务的主线程自然可以顺利启动了 

原文地址:https://www.cnblogs.com/bmy_light/p/2365149.html