如何从Windows服务运行exe文件,并在exe程序退出时停止服务?

问题描述:

我是使用Windows服务的完整初学者。我有一个基本的框架制定了服务,我目前在做这样的:如何从Windows服务运行exe文件,并在exe程序退出时停止服务?

protected override void OnStart(string[] args) 
    { 
     base.OnStart(args); 
     Process.Start(@"someProcess.exe"); 
    } 

刚刚火过的exe在程序的开始。

但是,我想从exe退出进程时停止服务本身。 我很确定我需要做某种线程(我也是一个初学者),但是我不确定它是如何工作的总体轮廓,也不是从本身阻止进程的具体方式。 你能帮我解决这个问题的一般过程吗(即从OnStart开始一个线程,然后什么......?)?谢谢。

您可以使用BackgroundWorker作为线程,使用Process.WaitForExit()等待进程终止,直到您停止服务。

你是对的,你应该做一些线程,在OnStart做大量的工作可能会导致启动服务时无法从Windows正确启动的错误。

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(); 
} 

编辑 您可能还需要到Process p移动到一个类的成员,并在OnStop停止该过程,以确保您可以再次停止该服务,如果EXE进入疯狂。

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

谢谢,这与我所希望的完全一样。 – xdumaine 2010-09-15 18:40:53

someProcess.exe应该有someLogic停止呼叫服务;)

使用ServiceController类。

// 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()); 

代码见从以上链接页面。

+0

谢谢,这看起来好像会达到最终结果 - 如果我正在开发exe文件。虽然这不是解决方案的更多解决方法吗?而且它只会在假设我正在编写.exe的情况下起作用。假设我无法访问exe的源代码,并且这应该仍然可以通过Windows服务本身来实现。 – xdumaine 2010-09-15 18:20:45

你必须使用一个ServiceController做到这一点,它有一个Stop方法。确保您的服务将CanStop属性设置为true。