在我的C#应用程序中,我定义并启动一个这样的过程:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WorkingDirectory = "Resources/";
startInfo.FileName = "batch.exe";
startInfo.CreateNoWindow = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.Arguments = "-h usb -o read";
Process process = new Process();
process.StartInfo = startInfo;
process.EnableRaisingEvents = true;
process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
process.CancelOutputRead();
process.Close();
我正在使用DataReceivedEvent来保存此输出:
void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != String.Empty && e.Data != null)
{
//Save data
result.Add(e.Data);
if (progressbar.InvokeRequired)
progressbar.Invoke(new ThreadStart(() =>
{
progressbar.PerformStep();
}));
else
progressbar.PerformStep();
}
}
同时,每次DataReceived事件触发时我都想更新进度条。我不知道调用进度条的代码有什么问题,但是线程永远不会被处理,更糟糕的是当应用程序到达代码部分时会锁定而不会抛出任何错误(在Visual Studio中进行调试时)。关于如何做到这一点的任何想法?谢谢!
答案 0 :(得分:2)
你的主线程卡在同步进程上.WaitForExit()调用 - 典型的死锁。 process_OutputDataReceived在另一个线程中运行,但Invoke不返回 - 主线程被WaitForExit阻止。
删除同步WaitForExit调用,订阅Process.Exited事件并在那里进行所有清理工作。