C# process.start,我怎么知道进程是否结束?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12273825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:43:01  来源:igfitidea点击:

C# process.start, how do I know if the process ended?

c#process

提问by Keltari

In C#, I can start a process with

在 C# 中,我可以用

process.start(program.exe);

process.start(program.exe);

How do I tell if the program is still running, or if it closed?

如何判断程序是否仍在运行,或者是否已关闭?

采纳答案by Austin Salonen

MSDN System.Diagnostics.Process

MSDN系统.诊断.过程

If you want to know right now, you can check the HasExitedproperty.

如果你现在想知道,你可以检查HasExited财产。

var isRunning = !process.HasExited;

If it's a quick process, just wait for it.

如果这是一个快速的过程,只需等待。

process.WaitForExit();

If you're starting one up in the background, subscribe to the Exited event after setting EnableRaisingEvents to true.

如果您在后台启动,请在将 EnableRaisingEvents 设置为 true 后订阅 Exited 事件。

process.EnableRaisingEvents = true;
process.Exited += (sender, e) => {  /* do whatever */ };

回答by Mike Atlas

Assign an event handler to the Exitedevent.

Exited事件分配一个事件处理程序。

There is sample code in that MSDN link - I won't repeat it here.

该 MSDN 链接中有示例代码 - 我不会在这里重复。

回答by Andrew Barber

Be sure you save the Processobject if you use the static Process.Start()call (or create an instance with new), and then either check the HasExitedproperty, or subscribe to the Exitedevent, depending on your needs.

Process如果您使用静态Process.Start()调用(或使用 创建实例new),请确保保存对象,然后根据您的需要检查HasExited属性或订阅Exited事件。

回答by Mike Mayer

Take a look at the MSDN documentation for the Process class.

查看Process 类MSDN 文档

In particular there is an event (Exited) you can listen to.

特别是有一个事件(Exited)您可以收听。

回答by coolmine

Process p = new Process();
p.Exited += new EventHandler(p_Exited);
p.StartInfo.FileName = @"path to file";
p.EnableRaisingEvents = true;
p.Start();

void p_Exited(object sender, EventArgs e)
{
    MessageBox.Show("Process exited");
}