Yog*_*ear 6 c# wpf stdout process
我在 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我的代码有问题吗?我应该与外部程序的程序员交谈吗?并要求他们用他们的代码做一些事情来引发我的事件?
谢谢
(可能)因为您阻塞了主线程,如果这是异步的,它将有时间做您的事情。
WaitForExit 不是异步的,因此如果您在主线程中运行此进程,它将保留所有内容直到完成。
我的建议是使 RunExternalExe 方法异步
public async string RunExternalExe(string filename, string arguments = null)
Run Code Online (Sandbox Code Playgroud)
和
await process.WaitForExitAsync();
Run Code Online (Sandbox Code Playgroud)
如果不可能,则在单独的线程中运行该进程并等待。
| 归档时间: |
|
| 查看次数: |
4460 次 |
| 最近记录: |