繁体   English   中英

从WPF调用时,流程执行时间过长

[英]Process execution takes too long when it is called from WPF

我有以下代码可以打开命令窗口(从WPF界面)并执行可能需要8-10分钟才能完成的代码:

ProcessStartInfo procStartInfo = new ProcessStartInfo();
procStartInfo.FileName = _exePath;
procStartInfo.Arguments = arguments;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = false;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;

using (Process pr = Process.Start(procStartInfo))
{
    pr.WaitForExit();
    string result = pr.StandardOutput.ReadToEnd();
    string[] split = result.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

    int output = 0;
    int.TryParse(split[split.Length - 1], out output);

    return output;
}

Program.cs我有使用以下方法更新状态(显示操作状态和百分比)的方法:

Console.Title = "Loading ... 5 %";

// do request to server and check status

while(status.InProgress) {
    Thread.Sleep(2000); // 2 seconds
    status = web.getJsonFromApiServer(url); // {InProgress: "true", Message: "Checking X%";       
}

有时进程会被挂起,并且其标题不再更新,就像发生无限循环一样。

如果我使用控制台而不是从WPF开始(我的意思是使用命令提示符,然后将位置设置为exe路径并使用参数运行它),那么它将正常工作,没有问题。

为什么会发生这种事情?

如果父进程在p.StandardOutput.ReadToEnd之前调用p.WaitForExit,并且子进程写入足够的文本以填充重定向的流,则可能导致死锁。 父进程将无限期地等待子进程退出。 子进程将无限期等待父进程从完整的StandardOutput流中读取。

为了避免死锁,您应该使用异步方法:

var procStartInfo = new ProcessStartInfo
{
    FileName = _exePath,
    Arguments = arguments,
    UseShellExecute = false,
    CreateNoWindow = false,
    RedirectStandardOutput = true,
    RedirectStandardError = true
};
var p = new Process { StartInfo = procStartInfo };
p.OutputDataReceived += (sender, eventArgs) => { Console.WriteLine(eventArgs.Data); };
p.Start();
p.BeginOutputReadLine();
p.WaitForExit();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM