2

私のサービスがインストールされると、インストール後にサービスを開始するハンドラーがあります。

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()関数を不適切に使用していますか?

4

3 に答える 3

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);
       }
   }
于 2012-05-25T17:28:30.780 に答える