[英]WaitforExit doesn't work correctly
所以我一直在與這個問題作斗爭一段時間,並嘗試了許多不同的方法來解決它,但不能。
基本上我的應用程序是調用java文件來加載設備上的應用程序。 當它正在加載它將它打印到richtext框時,我想轉到下一個文件。 我遇到的問題是,當第一個文件被加載時,第二個文件嘗試加載哪些情況問題。 我已經嘗試了等待退出,但如果我這樣做,那么輸出數據就不會寫入富文本框。 有任何想法嗎?
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");
}
}
下面兩種方法將stdout或錯誤寫入richtext字段。
//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
任何想法都會很棒。 基本上我需要退出進程,所以我可以繼續認為forloop加載下一個文件。
如果您使用WaitForExit,您的應用程序將阻塞(等待),直到該進程退出。 這意味着它無法在其UI線程中處理任何Windows消息,因此它不會更新UI。
您需要“在后台”啟動該過程,以便您的UI繼續刷新。 這可以通過以下方式完成:
坐在忙碌的等待循環中直到它完成,並處理應用程序事件。 (請注意這一點,因為任何導致對此代碼進行重入調用的事件都可能會造成非常糟糕的事情。通常,如果您使用此方法,您需要確保應用程序的其余部分在其知道的狀態下“鎖定”正在忙着等待一個過程完成)。 這實際上是WaitForExit所做的,但它也處理應用程序事件,允許UI保持模糊響應:
while (!process.HasExited) { Application.DoEvents(); Thread.Sleep(100); }
由於它是勸這里 ,設置process.EnableRaisingEvents =真正的解決了阻塞UI的問題,在我的情況。
我在這里可能完全錯了,但......
process1.StartInfo.Arguments = "-Xmx512M -jar";
process1.StartInfo.Arguments += toLoad;
你需要在-jar
之后有一個空格
否則Java會立即炸毀。
嘗試將WaitForExit
調用移出UI線程。
作為@M。 Babcock提到,你正在舉行富文本框的更新。
類似於此的解決方案可能有效:
修改btnLoad_Click
以啟動一個處理列表的新線程(這將在count> 0分支中)
Thread thread = new Thread(new ThreadStart(LoadPbThread));
thread.Start();
然后,添加:
void LoadPbThread()
{
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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.