简体   繁体   English

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

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

I have the following code which opens command window (from WPF interface) and executes code where can take long like @ 8-10 minutes: 我有以下代码可以打开命令窗口(从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;
}

And in Program.cs I have method which update status (show operation status and percent) with: 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%";       
}

Sometimes the process is hanged and its title is not updated anymore like something goes in infinite loop. 有时进程会被挂起,并且其标题不再更新,就像发生无限循环一样。

If I use console without starting from WPF ( I mean use command prompt and then set location to exe path and run it with arguments), it works fine, no issue. 如果我使用控制台而不是从WPF开始(我的意思是使用命令提示符,然后将位置设置为exe路径并使用参数运行它),那么它将正常工作,没有问题。

Why does this thing happens ? 为什么会发生这种事情?

A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardOutput.ReadToEnd and the child process writes enough text to fill the redirected stream. 如果父进程在p.StandardOutput.ReadToEnd之前调用p.WaitForExit,并且子进程写入足够的文本以填充重定向的流,则可能导致死锁。 The parent process would wait indefinitely for the child process to exit. 父进程将无限期地等待子进程退出。 The child process would wait indefinitely for the parent to read from the full StandardOutput stream. 子进程将无限期等待父进程从完整的StandardOutput流中读取。

To avoid deadlocks you should use asynchronous methods: 为了避免死锁,您应该使用异步方法:

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