void StartService(object parameter) { Service.InitStart(); // Run as SVC host if necessary. if (typeof(T).BaseType.Equals(typeof(MarshalByRefObject))) { // Create service var svcHost = new ServiceHost(Service); string info = GetInfo(Service.GetType().Name, svcHost); LogHelper.WriteInfo(info, EventLogEntryType.Information); // If you are getting "There is already a listener on IP endpoint 0.0.0.0:NNNN" error // but all processes who could use NNNN port is closed then maybe this ports is kept // open by Visual Studio debugger which tries to debug previously crashed executable. // Close Visual Studio debugger window in order to release resources and port. svcHost.Open(); } // Start actions. string st = ConfigurationManager.AppSettings["SimpleService_SleepTime"]; // Sleep 5 seconds if not specified. int sleepTime = string.IsNullOrEmpty(st) ? 5 : (int)TimeSpan.Parse(st).TotalSeconds; // Make sure that service initialized (for some reason locks doesn't work inside Service properly.); // Logical delay without blocking the current hardware thread. System.Threading.Tasks.Task.Delay(100).Wait(); while (!Service.IsStopping) { var watch = Stopwatch.StartNew(); bool skipSleep = false; if (!Service.IsPaused && !IsSessionEnded) { Service.DoAction((string[])parameter, ref skipSleep); } // If service finished sooner than expected. while (!skipSleep && watch.Elapsed.TotalSeconds < sleepTime) { if (Service.IsStopping || Service.IsPaused || IsSessionEnded) { break; } // Logical delay without blocking the current hardware thread. System.Threading.Tasks.Task.Delay(1000).Wait(); } } Service.InitEnd(); }