I am using for loop in my c# project.
I some cases I am iterating over 500,000 values - the GUI does not respond until the end of the loop.
Can I get the GUI to update inside the for
loop?
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.
Jason Hughes answered this above. Use the Refresh() of the control you are displaying your counter in:
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. Try use Application.DoEvents() method in loop. 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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.