exe进程退出时,如何从Windows服务运行exe并停止服务? [英] How to Run an exe from windows service and stop service when the exe process quits?

查看:230
本文介绍了exe进程退出时,如何从Windows服务运行exe并停止服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用Windows服务的完整入门者.我已经为该服务制定了基本框架,目前正在这样做:

I am a complete beginner to working with windows services. I have a basic skeleton worked out for the service and I am currently doing this:

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

仅在程序启动时启动exe.

just to fire-off the exe at the start of the program.

但是,我希望当从exe启动的进程退出时,服务自行停止. 我很确定我需要执行某种线程处理(也是我的初学者),但是我不确定这是如何工作的总体概述,也不能确定从内部停止进程的具体方法. 您能帮我完成此一般过程吗(即从OnStart启动线程,然后...?)?谢谢.

However, I'd like to have the service stop itself when the process started from the exe quits. I'm pretty sure I need to do some sort of threading (something I am also a beginner with), but I'm not sure of the overall outline of how this works, nor the specific way to stop a process from within itself. Could you help me with the general process for this (i.e. start a thread from OnStart, then what...?)? Thanks.

推荐答案

您可以使用 Process.WaitForExit() 等待直到您停止服务为止.

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

您正确地应该做一些线程处理,在OnStart中进行大量工作可能会导致启动服务时无法从Windows正确启动的错误.

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

修改 您可能还想将Process p移至类成员,并在OnStop中停止该过程,以确保如果exe出现问题,您可以再次停止该服务.

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

这篇关于exe进程退出时,如何从Windows服务运行exe并停止服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆