开发者

Restart Windows Service in c#

I got a link from SO Cannot restart a Service where it says to re开发者_StackOverflowstart the windows service.

The way it should restart the service is mentioned in the question as

public static void RestartService(string serviceName, int timeoutMilliseconds)
{
    ServiceController service = new ServiceController(serviceName);

    int millisec1 = Environment.TickCount;
    TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
    if (!(service.Status.Equals(ServiceControllerStatus.Stopped) || service.Status.Equals(ServiceControllerStatus.StopPending)))
    {
        service.Stop();
        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
    }
    // count the rest of the timeout
    int millisec2 = Environment.TickCount;
    timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));

    if (!(service.Status.Equals(ServiceControllerStatus.Running) || service.Status.Equals(ServiceControllerStatus.StartPending)))
    {
        service.Start();
        service.WaitForStatus(ServiceControllerStatus.Running, timeout);
    }
}

But i am not sure here, as to where to write the code. I need to restart the windows service as soon as that is installed from my application

Let me know if any input is needed.

Thanks!


I simply use net start and net stop to restart services. Example:

using System.Diagnostics;

public static void RestartService(string serviceName)
{
    var psi = new ProcessStartInfo("net.exe", "stop " + serviceName);
    psi.WindowStyle = ProcessWindowStyle.Hidden;
    psi.UseShellExecute = true;
    psi.WorkingDirectory = Environment.SystemDirectory;
    var st = Process.Start(psi);
    st.WaitForExit();

    psi = new ProcessStartInfo("net.exe", "start " + serviceName);
    psi.UseShellExecute = true;
    psi.WindowStyle = ProcessWindowStyle.Hidden;
    psi.WorkingDirectory = Environment.SystemDirectory;
    st = Process.Start(psi);
    st.WaitForExit();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜