How to Run an exe from windows service and stop service when the exe process quits?

狂风中的少年 提交于 2019-12-01 17:54:02

You can use a BackgroundWorker for the threading, use Process.WaitForExit() to wait for the process to terminate until you stop your service.

You're right that you should do some threading, doing lots of work in the OnStart may render errors about not starting correctly from Windows when starting the service.

protected override void OnStart(string[] args)
{

    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += new DoWorkEventHandler(bw_DoWork);
    bw.RunWorkerAsync();
}

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    Process p = new Process();
    p.StartInfo = new ProcessStartInfo("file.exe");
    p.Start();
    p.WaitForExit();
    base.Stop();
}

Edit You may also want to move the Process p to a class member and stop the process in the OnStop to make sure that you can stop the service again if the exe goes haywire.

protected override void OnStop()
{
    p.Kill();
}

You have to use a ServiceController to do it, it has a Stop method. Make sure your service has the CanStop property set to true.

someProcess.exe should have someLogic to stop the calling service ;)

Use the ServiceController class.

// Toggle the Telnet service - 
// If it is started (running, paused, etc), stop the service.
// If it is stopped, start the service.
ServiceController sc = new ServiceController("Telnet");
Console.WriteLine("The Telnet service status is currently set to {0}", 
                  sc.Status.ToString());

if  ((sc.Status.Equals(ServiceControllerStatus.Stopped)) ||
     (sc.Status.Equals(ServiceControllerStatus.StopPending)))
{
   // Start the service if the current status is stopped.

   Console.WriteLine("Starting the Telnet service...");
   sc.Start();
}  
else
{
   // Stop the service if its status is not set to "Stopped".

   Console.WriteLine("Stopping the Telnet service...");
   sc.Stop();
}  

// Refresh and display the current service status.
sc.Refresh();
Console.WriteLine("The Telnet service status is now set to {0}.", 
                   sc.Status.ToString());

Code is from the page linked above.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!