gpt4 book ai didi

.net 安装程序、自定义操作、停止和卸载 Windows 服务

转载 作者:行者123 更新时间:2023-12-02 05:03:02 25 4
gpt4 key购买 nike

我的 .net 安装程序应用程序将同时安装三个 Windows 应用程序时遇到问题。在这三个应用程序中,一个是 Windows 服务。因此,我的安装程序项目具有来自这三个 Windows 应用程序的三个主要输出。

安装后,所有这些都将按预期安装,Windows 服务将在安装后自动“启动”。

但是,如果我卸载该应用程序(当 Windows 服务处于“运行”模式时),安装程序将显示一个“正在使用的文件”对话框,最终会以服务未被卸载而其他东西会被卸载而告终被删除。但是,如果在卸载前停止Windows服务,则可以很好地完成。

我假设出现上述问题是因为安装程序应用程序将尝试删除 service.exe 文件(因为它也捆绑到安装程序中)。

我尝试了以下替代方案:

  1. 我试图通过添加一个自定义安装程序来解决这个问题,我试图在其中停止服务。但是,这似乎也不起作用。原因是,默认的“卸载”操作将在“卸载”自定义操作之前执行。 (失败)

  2. 将 Windows 服务应用程序的“主要输出”的“永久”属性设置为“真”。我假设安装程序将简单地跳过与主要输出相关的文件。但是(失败)

任何人都曾遇到过此类问题,请分享您的想法。

如何在卸载前停止服务,才能顺利完成卸载?

最佳答案

很久以前,我在使用 Windows 服务时遇到过类似的问题,并且能够通过调用 WaitForStatus(ServiceControllerStatus) 方法来解决它。该服务需要一些时间才能关闭,而您在服务完全停止之前继续操作。编写卸载逻辑以及当 Shutdown 状态停止时您想执行的任何操作。

如果您正在卸载并且想在卸载之前停止服务,那么您需要覆盖卸载自定义操作,添加代码来停止它,然后调用 base.Uninstall。请记住,限制为 15 秒的 WaitForStatus 可能不足以让服务关闭,具体取决于它的响应速度以及它在关闭时执行的操作。还要确保在 ServiceController 上调用 Dispose()(或在此示例中关闭),因为如果不这样做,内部服务句柄将不会立即释放, 如果它仍在使用中,则无法卸载该服务。

MSDN link

这只是如何在 EventLogger 中实现和记录的示例:

public override void Uninstall(System.Collections.IDictionary savedState)
{
ServiceController controller = new ServiceController("My Service");
try
{
if (controller.Status == ServiceControllerStatus.Running | controller.Status == ServiceControllerStatus.Paused)
{
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 0, 30));
controller.Close();
}
}
catch (Exception ex)
{
string source = "My Service Installer";
string log = "Application";
if (!EventLog.SourceExists(source))
{
EventLog.CreateEventSource(source, log);
}
EventLog eLog = new EventLog();
eLog.Source = source;
eLog.WriteEntry(string.Concat(@"The service could not be stopped. Please stop the service manually. Error: ", ex.Message), EventLogEntryType.Error);
}
finally
{
base.Uninstall(savedState);
}
}

关于.net 安装程序、自定义操作、停止和卸载 Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14477949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com