所以我一直在与这个问题作斗争,并尝试了很多不同的方法来解决它,但都无法解决。
基本上,我的应用所做的就是调用 java 文件以在设备上加载应用。在加载时将其打印到富文本框,然后我想转到下一个文件。我遇到的问题是,在加载第一个文件时,第二个文件尝试加载哪些案例有问题。我已尝试等待退出,但如果我这样做,则输出数据不会写入富文本框。有什么想法吗?
private void btnLoad_Click(object sender, EventArgs e)
{
rchsdtOut.Clear();
//count the items in queue.
var count = lstBarToLoad.Items.Count;
if (count <= 0)
{
MessageBox.Show("Nothing added to the load queue");
}
else
{
String toLoad;
for (int i=0; i < count;i++)
{//START OF FOREACH
toLoad = lstBarToLoad.Items[i].Text;
//call load method.
loaddPB(toLoad);
}//end of for.
}//end of else.
}//end of private
我试过在许多不同的地方等待退出,但它似乎不起作用。
//Method to load files on device.
private void loaddPB(string toLoad)
{
process1 = new System.Diagnostics.Process();
process1.StartInfo.UseShellExecute = false;
process1.StartInfo.RedirectStandardOutput = true;
process1.StartInfo.RedirectStandardError = true;
process1.StartInfo.CreateNoWindow = true;
process1.StartInfo.FileName = "java.exe ";
process1.StartInfo.Arguments = "-Xmx512M -jar";
process1.StartInfo.Arguments += toLoad;
try
{
process1.Start();
process1.OutputDataReceived += (s, a) => myMethod(a);
process1.BeginOutputReadLine();
process1.ErrorDataReceived += (s, a) => myErrorMethod(a);
process1.BeginErrorReadLine();
process1.WaitForExit();
}
catch
{
Console.WriteLine("error");
}
}
以下两种方法将标准输出或错误写入富文本字段。
//Method to do the logging.
private void myMethod(DataReceivedEventArgs e)
{
if (e.Data != null)
{
Action action = () => rchsdtOut.Text += "\r\n" + e.Data.ToString();
rchsdtOut.BeginInvoke(action, null);
Console.WriteLine(e.Data.ToString());
}
}//end of private
//Method to load the error if any thrown.
private void myErrorMethod(DataReceivedEventArgs e)
{
if (e.Data != null)
{
Action action = () => rchsdtOut.Text += "\r\n" + e.Data.ToString();
rchsdtOut.BeginInvoke(action, null);
Console.WriteLine(e.Data.ToString());
}
}//end of private
任何想法都会很棒。 Bascally 我需要进程退出,然后我可以继续认为 forloop 加载下一个文件。
最佳答案
如果您使用 WaitForExit,您的应用程序将阻塞(等待)直到进程退出。这意味着它无法在其 UI 线程中处理任何 Windows 消息,因此它不会更新 UI。
您需要“在后台”启动该过程,以便您的 UI 继续刷新。这可以通过以下方式完成:
- 从单独的线程启动和监控进程,并将进度信息传回 UI 线程进行显示
- 向进程退出事件添加事件处理程序,或定期轮询 process.HasExited 标志,并使用它来了解第一个进程何时完成。您的事件处理程序将启动此进程,然后退出回到您的主应用程序循环,以便它在等待外部进程完成时正常运行。
进入繁忙的等待循环,直到它完成,然后处理应用程序事件。 (当心这一点,因为任何导致重入调用此代码的事件都可能造成非常糟糕的后果。通常,如果您使用这种方法,您需要确保应用程序的其余部分在它知道的状态下“锁定”正忙于等待进程完成)。这实际上是 WaitForExit 所做的,但它也处理应用程序事件,允许 UI 保持模糊响应:
while (!process.HasExited) { Application.DoEvents(); Thread.Sleep(100); }
关于c# - WaitforExit 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9213569/