【发布时间】: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 我应该改用哪个命令?