如何在 Server 2019 Datacenter 上重启 Windows 服务?

How can I restart a Windows service on Server 2019 Datacenter?

我在 Windows 家庭版上成功重启了 Windows 服务,但是当我 运行 应用程序在 Windows 上重启 Windows 服务时Server 2019 Datacentre 安装,出现此错误:

Error 103: The service did not respond to the start or control request in a timely fashion.

public static void EndTask()
{
    string taskname = "serviceTask.exe";
    string processName = taskname.Replace(".exe", "");

    foreach (Process process in Process.GetProcessesByName(processName))
    {
        process.Kill();
        process.WaitForExit();
        process.Dispose();
    }
}
       
msg = string.Empty;
if (serviceName != "")
{
    ServiceController service = new ServiceController(serviceName);
    try
    {
        EndTask();

        int millisec1 = Environment.TickCount;
        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
        var serviceExists = ServiceController.GetServices().Any(s => s.ServiceName == serviceName);
        if (serviceExists)
        {
            if (service.Status == ServiceControllerStatus.Running)
            {
                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
            }

            // count the rest of the timeout
            int millisec2 = Environment.TickCount;
           timeout = TimeSpan.FromMilliseconds(timeoutMillisecond - (millisec2 - millisec1));

            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running, timeout);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}
else
{
    msg = "service not started";

}

用户具有管理员权限,可以从“服务”面板启动和停止服务,但不能从 C# 启动和停止。这是我用来重启的过程。是否需要在 Server 2019 上做一些不同的事情?

您的服务似乎在服务启动时处理了一些耗时的任务。要增加服务超时,您可以遵循 this video 或者您可以使用计时器绕过服务启动时间的耗时任务,该计时器将在 5 秒或其他时间后触发,这样服务就可以启动而无需额外时间.