Tiphanie Aubry
Tiphanie Aubry

Reputation: 11

Topshelf TimeoutException

I'm trying to use Topshelf Framework to create a windows service. But when i try to start the service, there is this exception :

" The service failed to start... System.Service.Process.TimeoutException : the waiting period has expired and the operation has not been completed"

This is my code :

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

} 

Thanks for any help :)

Upvotes: 1

Views: 1361

Answers (1)

Sudhanshu Mishra
Sudhanshu Mishra

Reputation: 6733

There are several issues I notice: The current code would make the timer fire only once (you have AutoReset = false)

with TopShelf, the MyService class should look like this:

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

and the console app/ Program.cs will look like so:

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

Upvotes: 1

Related Questions