在 C# 中卸载时,如何检查 <service>.exe 上的锁是否已释放?

How to check if lock is released on <service>.exe while uninstalling in C#?

当尝试卸载应用程序时,我们尝试先停止服务并确保 WaitForStatus 报告成功。然后我们使用 sc delete 删除它们,但有时并非所有文件都从已安装的文件夹中删除。我们可以手动删除它们,但在几秒钟后左右,这也会使 pc 与另一台 pc 不同。在这里,我们认为 windows 对某些文件(主要是 service.exe)是 holding/locking,因此无法删除它们和所有其他相关文件。

我们想要实现的是在我们成功删除 <service>.exe 之后,我们想要检查(比如,在 while 循环中)锁是否仍在 <service>.exe,如果是则休眠持续 2 秒,然后重新检查,直到它被释放,然后继续卸载文件。这可能需要大约 30 秒,但由于它因个人电脑而异,我们希望稳健而不是随机等待。 我们如何检查文件 (service.exe) 是否被锁定?根据我的研究,我没有看到直接的解决方案。每个人都建议检查 file.Open (FileMode.Open, FileAccess.Read, FileShare.None)。这似乎是不必要的。有直接的解决方案吗?

下面是我们如何停止和删除服务的代码。

try
{
   service= new ServiceController(serviceName);
   service.Stop();
   service.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 60));
   service.Refresh();
   if (service.Status == ServiceControllerStatus.Stopped)
   {
        //runs command with sc delete 'servicename'
        return RunCommand("cmd.exe", "/c sc delete \"" + serviceName + "\"");
   }
}
catch()
{
 ...
}

对于一些可能感兴趣的人,我们通过尝试在 while 循环中删除 service.exe 来解决这个问题,然后重新尝试直到它被删除。在重试之前我们睡了 1 秒。我们还应该限制重试次数,否则我们可能最终会冻结卸载。希望这对有类似用例的人有帮助