The entry method (public void Main()) must return within 30 seconds or the service appears to not start.
Unlike other types of application, returning from the entry method in a Service will not end the process unless there is nothing else running. When I create a service, I will instantiate as little as possible, set up a timer event (or infinite loop in a second thread), then return to the entry method:
static class Program
{
static void Main()
{
if (!Debugger.IsAttached)
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Watcher()
};
ServiceBase.Run(ServicesToRun);
}
else
{
(new Watcher()).Start();
Thread.Sleep(Timeout.Infinite);
}
}
}
private static Timer _timer;
private int _timerIntervalSeconds = 10;
private static MessageQueueParser _messageQueueParser;
static BackgroundWorker _backgroundWorker;
static DataParser _DataParser;
public Watcher()
{
Initialize();
CanPauseAndContinue = true;
ServiceName = "Watcher Service";
_timer = new Timer(_timerIntervalSeconds * 1000);
_timer.Elapsed += OnTimerElapsed;
_messageQueueParser = new MessageQueueParser();
_backgroundWorker = new BackgroundWorker {WorkerSupportsCancellation = false};
_backgroundWorker.RunWorkerCompleted += WorkerRunWorkerCompleted;
_backgroundWorker.DoWork += WorkerThreadDoWork;
_DataParser = new DataParser();
}
private static bool _isBusy;
void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
if (_isBusy)
{
if (!_backgroundWorker.IsBusy)
_isBusy = false;
return;
}
_isBusy = true;
_backgroundWorker.RunWorkerAsync();
}
This is an extended example as it's what I'm working on atm. There will be more interaction with the config on startup but the concept is there.
Hope that helps
Don't forget to like and subscribe :P