【问题标题】:Process.OutputDataReceived not firingProcess.OutputDataReceived 未触发
【发布时间】:2020-01-05 12:46:07
【问题描述】:

我在 WPF 项目中有一个简单的函数。我有一个进度条,我希望在外部程序运行命令时更新进度条。奇怪的是,它只在外部程序完成时更新。

外部程序编辑特定文件夹中的所有图片,当它完成编辑图片时,它正在写入一个新行。

public string RunExternalExe(string filename, string arguments = null)
    {
        var process = new Process();

        process.StartInfo.FileName = filename;
        if (!string.IsNullOrEmpty(arguments))
        {
            process.StartInfo.Arguments = arguments;
        }

        process.StartInfo.CreateNoWindow = true;
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.StartInfo.UseShellExecute = false;

        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.RedirectStandardOutput = true;

        var stdOutput = new StringBuilder();

        // Use AppendLine rather than Append since args.Data is one line of output, not including the newline character.
        process.OutputDataReceived += (sender, args) =>
        {
            bgwMain.ReportProgress(i+=2);
            //Console.WriteLine(args.Data);
            //stdOutput.AppendLine(args.Data);
        };

        try
        {
            process.Start();
            process.BeginOutputReadLine();

            process.WaitForExit();
        }
        catch (Exception e)
        {
            throw new Exception("OS error while executing " , e);
        }

        if (process.ExitCode == 0)
        {
            return stdOutput.ToString();
        }
        else
        {

            throw new Exception("finished with exit code = " + process.ExitCode);
        }
    }

我的代码有问题吗? 我应该与外部程序的程序员交谈吗?并要求他们用他们的代码做一些会引发我的事件的事情?

谢谢

【问题讨论】:

  • 你必须将process.EnableRaisingEvents设置为true
  • @FarhadJabiyev 没用:/
  • 我怀疑问题出在 WaitForExit 上。您正在调用的应用程序正在关闭标准输出,因此您的 c# 应用程序正在等待。
  • @jdweng 我应该改用哪个命令?

标签: c# wpf process stdout


【解决方案1】:

这(可能)是因为你阻塞了主线程,如果这是异步的,它会有时间做你的事情。

WaitForExit 不是异步的,因此如果您在主线程中运行此进程,它将暂停所有内容直到完成。

我的建议是使 RunExternalExe 方法异步

public async string RunExternalExe(string filename, string arguments = null)

await process.WaitForExitAsync();

如果这不可能,则在单独的线程中运行该进程并等待。

【讨论】:

    猜你喜欢
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2020-11-26
    • 2013-08-28
    相关资源
    最近更新 更多