让进程终止。

我有一个进程对象的设置如下:

Process p = new Process();
p.StartInfo.FileName = command;
p.StartInfo.UseShellExecute = true;
p.StartInfo.Arguments = String.Format(
    commandArguments,
    destinationLocation,
    sourceLocation,
    sourceDirName,
    (string.IsNullOrEmpty(revisionNotes.Text)) ? "" : revisionNotes.Text);

(未定义的值由外部提供并且是有效的)。该进程启动并利用 p.Start(); 正确执行,但是我需要在终止时捕获它。控制台窗口短暂地闪烁并消失,这似乎表明进程已经完成,但是没有触发任何相关的事件( OutputDataRecieved、Exited等),这就像进程无限期地存在一样。(我正在尝试使用一些参数执行一个 Lua 脚本,如果这对问题有关,请问有人能帮助我正确地停止这个进程吗?

原文链接 https://stackoverflow.com/questions/1818427

点赞
stackoverflow用户29407
stackoverflow用户29407

WaitForExit

等待关联进程退出。

public void WaitForExit ();

备注

此方法将阻止调用线程,直到关联进程退出。 此方法还可以使调用线程等待一段时间(以毫秒为单位),以便进程有机会退出,并在此期间锁定主机。 若要避免锁定主机并等待无限期地,请使用 WaitForExit(Int32) 方法。

public bool WaitForExit (int milliseconds);

示例

using System;
using System.Diagnostics;

namespace ConsoleApplication
{
    class Program
    {
        public static void Main(string[] args)
        {
            Process p = new Process();

            // set up process start info
            p.StartInfo.FileName = "ping.exe";
            p.StartInfo.Arguments = "www.microsoft.com";

            // start the process
            p.Start();

            Console.WriteLine("Process Started ...");

            // wait for the process to exit
            p.WaitForExit();

            Console.WriteLine("Process Exited ...");
        }
    }
}
2009-11-30 08:11:23
stackoverflow用户147776
stackoverflow用户147776

你是否将进程的 EnableRaisingEvents 属性设为True了?如果没有,你将无法捕获到Exited事件。

2009-11-30 08:12:02