【问题标题】:Topshelf TimeoutExceptionTopshelf 超时异常
【发布时间】:2015-11-29 01:24:01
【问题描述】:

我正在尝试使用 Topshelf 框架来创建 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;
    }

} 

感谢您的帮助:)

【问题讨论】:

    标签: exception timeout topshelf


    【解决方案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;
            }
        }
    }
    

    控制台应用程序/ 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"); 
                });
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-12
      • 1970-01-01
      • 2020-03-16
      • 2022-01-18
      • 1970-01-01
      • 2015-01-28
      • 2013-06-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多