![](/img/trans.png)
[英]How can i update in live real time listBox adding items from another class?
[英]How can I update the GUI with live results from a for loop?
我在c#項目中使用for循環。
在某些情況下,我要遍歷500,000個值-GUI直到循環結束才響應。
我可以在for
循環中更新GUI嗎?
for (int i = 0; i < 100000; i++)
{
double s1 = rnd.NextDouble();
double s2 = rnd.NextDouble();
w = Math.Sqrt(-2 * Math.Log(s1)) * Math.Cos(2 * Math.PI * s2);
listBox1.Items.Add(w.ToString());
}
我執行此操作的最佳方法是啟動一個線程以文本填充控件,為此您需要從線程內部調用方法以填充列表框,並且需要委托方法,
在您的課程中聲明一個委托方法,
delegate void SetListBoxDelg(string value);
然后啟動一個線程,該線程將啟動填充列表框的過程,
Thread t = new Thread(StartProc);
t.Start();
這是您在其中調用用於填充列表框的方法的線程代碼,
public void StartProc()
{
for (int i = 0; i < 100000; i++)
{
double s1 = rnd.NextDouble();
double s2 = rnd.NextDouble();
w = Math.Sqrt(-2 * Math.Log(s1)) * Math.Cos(2 * Math.PI * s2);
SetListBox(w.ToString());
}
}
這是從線程內部調用的方法,
private void SetListBox(string value)
{
if (this.InvokeRequired)
{
SetListBoxDelg dlg = new SetListBoxDelg(this.SetListBox);
this.Invoke(value);
return;
}
listBox1.Items.Add(value);
}
嘗試這個:
for (int i = 0; i < 100000; i++)
{
label.Text = i;
double s1 = rnd.NextDouble();
double s2 = rnd.NextDouble();
w = Math.Sqrt(-2 * Math.Log(s1)) * Math.Cos(2 * Math.PI * s2);
listBox1.Items.Add(w.ToString());
}
用標簽名稱替換label.Text。
傑森·休斯在上面回答了這一問題。 使用顯示計數器的控件的Refresh():
for (int i = 0; i < 100000; i++)
{
labelIteration.Text = i.ToString();
labelIteration.Refresh();
double s1 = rnd.NextDouble();
double s2 = rnd.NextDouble();
w = Math.Sqrt(-2 * Math.Log(s1)) * Math.Cos(2 * Math.PI * s2);
}
如果它是單線程應用程序,則您可能會凍結GUI。 嘗試在循環中使用Application.DoEvents()方法。 例如:
for (int i = 0; i < 100000; i++)
{
labelToShow.Text = i.ToString(); // live update of information on the GUI
labelToShow.Invalidate();
Application.DoEvents();
double s1 = rnd.NextDouble();
double s2 = rnd.NextDouble();
w = Math.Sqrt(-2 * Math.Log(s1)) * Math.Cos(2 * Math.PI * s2);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.