代码之家  ›  专栏  ›  技术社区  ›  Snake Eyes

当从WPF调用流程执行时,它花费的时间太长

  •  2
  • Snake Eyes  · 技术社区  · 7 年前

    我有以下代码,可以打开命令窗口(从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启动(我的意思是使用命令提示符,然后将location设置为exe path并使用参数运行它),它可以正常工作,没有问题。

    为什么会发生这种事?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Sani Huttunen    7 年前

    如果父进程调用 P.WaistFurEv.P.Stutabutou.Read toEnter和子进程之前 写入足够的文本以填充重定向流。父进程 将无限期等待子进程退出。孩子 进程将无限期等待父进程读取完整的 标准输出流。

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

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