首页 > 解决方案 > 无法更新我自己的 Windows 服务,因为它正被另一个进程使用

问题描述

我创建了一个应用程序来更新 Windows 服务应用程序(我也创建了)。这个“更新程序”应用程序就像一个魅力,但前提是 Windows 服务已经停止。

更新程序应用程序的操作顺序如下:

  1. 获取ServiceController对象
  2. 呼叫myService.Stop()(如果尚未处于该ServiceControllerStatus.Stopped状态)
  3. 称呼myService.WaitForStatus()
  4. 称呼myService.Close()
  5. 更新所有 .dll 文件
  6. 称呼myService.Start()
  7. 称呼myService.Close()

如果服务已经停止,那么这确实有效。但是,如果该服务之前正在运行,则更新程序应用程序将停止该服务并继续执行第 5 步。此时,我将收到一条错误消息,指出我无法覆盖 .dll 文件,因为这些文件正在被另一个进程使用。

起初,我认为是我自己的更新程序应用程序通过ServiceController对象保持对服务的引用,而当我添加步骤 #4 时,这并没有改变任何东西。

如果我两次运行更新程序应用程序,第一次它会停止它并在更新 .dll 文件时失败。然后它第二次注意到它已经停止并尝试更新 .dll 文件,然后一切正常。服务 .dll 得到更新并启动服务。

private static bool ServiceCommand(string serviceName, bool startService, TimeSpan timeout)
{
    if (!GetServiceObject(serviceName, out ServiceController service)) return false;

    try
    {
        // First, check to make sure it's not already started or stopped
        if (service.Status == (startService ? ServiceControllerStatus.Running : ServiceControllerStatus.Stopped))
        {
            return true;
        }

        ServiceControllerStatus myTargetStatus;
        if (startService)
        {
            service.Start();
            myTargetStatus = ServiceControllerStatus.Running;
        }
        else
        {
            service.Stop();
            myTargetStatus = ServiceControllerStatus.Stopped;
        }

        // Wait for the target status
        service.WaitForStatus(myTargetStatus, timeout);

    }
    catch (Exception e)
    {
        Logger.Log("Unable to " + (startService ? "start" : "stop") + " service '" + service.ServiceName + "': " + e.Message);
        return false;
    }
    finally
    {
        if (service != null) service.Close();
    }

    return true;
}

我相信这就是问题所在。在第 5 步中,我所做的只是File.Copy()将 override 参数设置为 true。这是我收到错误消息的地方The process cannot access the file '' because it is being used by another process.

非常感谢任何帮助或输入!谢谢!

标签: c#.netservicewindows-services

解决方案


可执行文件可以向服务控制管理器报告服务已停止,但可执行文件可以继续运行一段时间,例如清理内容或让后台线程完成其工作。它不应该那样做,在这种情况下它应该请求更多的关闭时间,但这可能就是正在发生的事情。

因此,要么修复您的服务,使其可执行文件在报告服务停止状态后立即停止,要么在复制文件之前等待可执行文件停止。

另请参阅ServiceController.Stop() 后服务未完全停止windows 服务等待处理停止请求的最长时间以及如何请求额外时间


推荐阅读