/// <summary>
/// Start the service with the given name and wait until the status of the service is running.
/// If the service status is not running after the given timeout then the service is considered not started.
/// You can call this method after stop or pause the service in order to re-start it.
/// </summary>
/// <param name="serviceName">The name of the service</param>
/// <param name="timeout">The timeout.</param>
/// <returns>True if the service has been started. Otherwise, false.</returns>
public static bool StartService(string serviceName, TimeSpan timeout)
{
try
{
bool timeoutEnabled = (timeout.CompareTo(TimeSpan.Zero) > 0);
using (ServiceController c = new ServiceController(serviceName))
{
c.Refresh();
if (timeoutEnabled && c.Status == ServiceControllerStatus.Running)
return true;
if (!timeoutEnabled && (c.Status == ServiceControllerStatus.Running || c.Status == ServiceControllerStatus.StartPending || c.Status == ServiceControllerStatus.ContinuePending))
return true;
if (c.Status == ServiceControllerStatus.Paused || c.Status == ServiceControllerStatus.ContinuePending)
c.Continue();
else if (c.Status == ServiceControllerStatus.Stopped || c.Status == ServiceControllerStatus.StartPending)
c.Start();
if (timeoutEnabled)
c.WaitForStatus(ServiceControllerStatus.Running, timeout);
return true;
}
}
catch (Exception e)
{
Utils.Trace(e, "Unexpected error starting service {0}.", serviceName);
return false;
}
}