c# - 无法更新我自己的 Windows 服务,因为它正被另一个进程使用
问题描述
我创建了一个应用程序来更新 Windows 服务应用程序(我也创建了)。这个“更新程序”应用程序就像一个魅力,但前提是 Windows 服务已经停止。
更新程序应用程序的操作顺序如下:
- 获取
ServiceController
对象 - 呼叫
myService.Stop()
(如果尚未处于该ServiceControllerStatus.Stopped
状态) - 称呼
myService.WaitForStatus()
- 称呼
myService.Close()
- 更新所有 .dll 文件
- 称呼
myService.Start()
- 称呼
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.
非常感谢任何帮助或输入!谢谢!
解决方案
可执行文件可以向服务控制管理器报告服务已停止,但可执行文件可以继续运行一段时间,例如清理内容或让后台线程完成其工作。它不应该那样做,在这种情况下它应该请求更多的关闭时间,但这可能就是正在发生的事情。
因此,要么修复您的服务,使其可执行文件在报告服务停止状态后立即停止,要么在复制文件之前等待可执行文件停止。
另请参阅ServiceController.Stop() 后服务未完全停止,windows 服务等待处理停止请求的最长时间以及如何请求额外时间。
推荐阅读
- android - 无法更新安卓工作室
- typescript - 在 Typescript 中创建 fetch 包装器
- python - Keras中的“trainable_weights”是什么意思?
- regex - Visual Studio 多行替换,同时在查找时忽略前导空格,但在替换时包括它们
- javascript - 围绕整个多边形布线
- android-studio - 应用程序在发布之前是否应该完全没有错误?
- spring-security - Spring social 和 oauth2 协议有什么关系?
- java - 当我调用一个功能是切换到模块内的活动的模块时,我的应用程序崩溃了
- gcc - 为什么我不能使用 GCC 编译 ARM BE8 ELF?
- git - Visual Studio 代码终端“git add .”发送以下错误消息“致命:不是 git 存储库(或任何父目录):.git”