2012-05-25 111 views
1

当我的服务安装时,我有一个处理程序在安装后启动服务。卸载时自动停止Windows服务

private void InitializeComponent() 
{ 
    ... 
    this.VDMServiceInstaller.AfterInstall += ServiceInstaller_AfterInstall; 
} 


private void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e) 
{ 
    ServiceController sc = new ServiceController("MyService"); 
    sc.Start(); 
} 

我想停止该服务被卸载之前,所以我增加了一个额外的处理程序的InitializeComponent()。

this.ServiceInstaller.BeforeUninstall += ServiceInstaller_BeforeUninstall; 

,并添加了功能:

private void ServiceInstaller_BeforeUninstall(object sender, InstallEventArgs e) 
{ 
    try 
    { 
     ServiceController sc = new ServiceController("MyService"); 
     if (sc.CanStop) 
     { 
      sc.Stop(); 
      sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped); 
     } 
    } 
    catch (Exception exception) 
    {} 
} 

但服务不卸载前停止。我是否正确使用ServiceController.Stop()函数?

回答

1

将类似下面的帮助你:

protected override void OnBeforeUninstall(IDictionary savedState) 
    { 
     ServiceController controller = new ServiceController("ServiceName"); 

     try 
     { 

      if(controller.Status == ServiceControllerStatus.Running | controller.Status == ServiceControllerStatus.Paused) 
      { 
      controller.stop(); 
      } 
      controller.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0,0,0,15)); 

      controller.Close(); 
     } 
     catch(Exception ex) 
     { 
      EventLog log = new EventLog(); 
      log.WriteEntry("Service failed to stop"); 
     } 

     finally 
     { 
      base.OnBeforeUninstall(savedState); 
     } 
    } 
+0

不起作用。它几乎就像该函数不会被调用,因为该函数也应该引发BeforeUninstall事件。 –

0

这是我试图阻止窗口:我已经测试了所有替代现有

Locked files dialog

,并执行他们没有在提示关闭应用程序的对话框出现之前。

甚至没有类构造函数足够早。

我的结论是,作为安装程序项目,您不能通过代码停止服务,在对话框之前。

由于没有其他方法可以在项目中执行代码,我没有看到任何方法来实现这一点。

我真的很希望它有所不同,因为我自己非常需要这个,但是安装程序项目中没有任何“挂钩”,它可以及早进入以解决问题。


我最好的建议是做两个安装程序。

其中一个充当第二个包装器,在安装时正常启动第二个安装器。

但是在卸载时,它先停止服务,然后卸载第二个。

但是这对我来说太过分了,所以我还没有进一步探索这个。