Topshelf TimeoutException

时间:2015-09-03 09:23:56

标签: exception timeout topshelf

我正在尝试使用Topshelf Framework来创建Windows服务。但是,当我尝试启动该服务时,有一个例外:

“服务无法启动... System.Service.Process.TimeoutException:等待期已过,操作尚未完成”

这是我的代码:

public class MyService : ServiceControl
{

    private System.Timers.Timer _timer;

    public void MyService()
    {
        _timer = new System.Timers.Timer(10);
        _timer.AutoReset = false;
        _timer.Elapsed += new ElapsedEventHandler(TimerOnElapsed);
    }

    private void TimerOnElapsed(object source, ElapsedEventArgs e)
    {
        //all the operation to do at the startup
    }

    public bool Start(HostControl hostControl)
    {
        _timer.Start();
        return true;
    }

    public bool Stop(HostControl hostControl)
    {
        _timer.Stop();
        return true;
    }

} 

感谢您的帮助:)

1 个答案:

答案 0 :(得分:1)

我注意到几个问题: 当前代码只会使计时器触发一次(你有AutoReset = false)

使用TopShelf,MyService类应该如下所示:

using System.Timers;
using Topshelf;

namespace TopShelfTestService
{
    public class MyService
    {
        private System.Timers.Timer _timer;

        public MyService()
        {
            _timer = new System.Timers.Timer(10);
            _timer.AutoReset = true;
            _timer.Elapsed += new ElapsedEventHandler(TimerOnElapsed);
        }

        private void TimerOnElapsed(object source, ElapsedEventArgs e)
        {
            //all the operation to do at the startup
        }

        public bool Start(HostControl hostControl)
        {
            _timer.Start();
            return true;
        }

        public bool Stop(HostControl hostControl)
        {
            _timer.Stop();
            return true;
        }
    }
}

,控制台app / Program.cs看起来像这样:

using Topshelf;

namespace TopShelfTestService
{
    class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                x.Service<MyService>(s =>
                {
                    s.ConstructUsing(name => new MyService());
                    s.WhenStarted((tc, hostControl) => tc.Start(hostControl));
                    s.WhenStopped((tc, hostControl) => tc.Stop(hostControl));
                });
                x.RunAsLocalSystem();

                x.SetDescription("Sample Topshelf Host");        //7
                x.SetDisplayName("Test Service with TopShelf");                       //8
                x.SetServiceName("TopShelfTestService"); 
            });
        }
    }
}