[英]How can I update the GUI with live results from a for loop?
I am using for loop in my c# project. 我在c#项目中使用for循环。
I some cases I am iterating over 500,000 values - the GUI does not respond until the end of the loop. 在某些情况下,我要遍历500,000个值-GUI直到循环结束才响应。
Can I get the GUI to update inside the for
loop? 我可以在
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());
}
The best way I have done this is by starting a thread to populate a control item with text for that you would need to call a method from inside the thread to populate the listbox and that requires a delegate method, 我执行此操作的最佳方法是启动一个线程以文本填充控件,为此您需要从线程内部调用方法以填充列表框,并且需要委托方法,
Declare a delegate method in your class, 在您的课程中声明一个委托方法,
delegate void SetListBoxDelg(string value);
then start a thread that will start this process of populating the listbox, 然后启动一个线程,该线程将启动填充列表框的过程,
Thread t = new Thread(StartProc);
t.Start();
this is the thread code where you call the method to populate your listbox, 这是您在其中调用用于填充列表框的方法的线程代码,
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());
}
}
And here is the method that is called from inside of the thread, 这是从线程内部调用的方法,
private void SetListBox(string value)
{
if (this.InvokeRequired)
{
SetListBoxDelg dlg = new SetListBoxDelg(this.SetListBox);
this.Invoke(value);
return;
}
listBox1.Items.Add(value);
}
Try this: 尝试这个:
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());
}
Replace label.Text with your label's name. 用标签名称替换label.Text。
Jason Hughes answered this above. 杰森·休斯在上面回答了这一问题。 Use the Refresh() of the control you are displaying your counter in:
使用显示计数器的控件的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);
}
If it is single-threaded application you can get froze of you GUI. 如果它是单线程应用程序,则您可能会冻结GUI。 Try use Application.DoEvents() method in loop.
尝试在循环中使用Application.DoEvents()方法。 For example:
例如:
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.