问题描述
我想显示一个进度条或任何反映我的变量i值的东西,例如通过数百万次循环进行循环:
I want to show a progess bar or any thing reflecting the value of the variable i of mine when looping it through millions of loops like this:
for(int i = 0;i<1000000;i++)
{
//How to updating its value to the user?
}
放置在循环中的任何命令,例如"label1.Text= i.ToString()
"都将不起作用.
您能告诉我如何实现吗?
非常感谢您!
Any commands like "label1.Text= i.ToString()
" placed in the loop won''t work.
Could you please tell me how to achieve that?
Thank you very much!
推荐答案
int num = 1000000;
progressBar1.Maximum = num;
for (int i = 0; i < num; i++)
{
progressBar1.Value = i;
}
如果像这样使用BackgroundWorker,也可以使用标签
Also you could use a label if you use a BackgroundWorker like so
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int num = 1000000;
for (int i = 0; i < num; i++)
{
UpdateLabel(i);
}
}
private delegate void UpdateLabelCallback(int val);
private void UpdateLabel(int val)
{
if (label1.InvokeRequired)
{
UpdateLabelCallback ulc = new UpdateLabelCallback(UpdateLabel);
label1.Invoke(ulc, new object[] { val });
}
else
{
label1.Text = val.ToString();
}
}
if (i % 100000 == 0 || i == 1000000 - 1) {
label1.Text = i.ToString();
}
为了使它正常工作,您将必须在另一个线程中执行整个循环,然后必须在UI线程上执行label1.Text的分配(您可以在此处找到如何执行此操作:).
根据您的实际操作,更好的方法可能是每隔一定的时间间隔(例如,每秒)更新一次屏幕.您可以使用计时器来执行此操作.看起来像这样:
For that to work properly, you will have to execute the entire loop in a different thread and then the assignment of label1.Text will have to execute on the UI thread (you can find out how to do that here: Changing a WinForms Control on the ''UI'' Thread from another Thread).
Depending on exactly what you are doing, a better way is probably to update the screen on some interval (e.g., every second). You can do this with a timer. That would look something like this:
ThreadStart ts = new ThreadStart(delegate()
{
int j = 0;
bool done = false;
ThreadStart invoker = null;
invoker = new ThreadStart(delegate()
{
if (this.InvokeRequired)
{
Thread.Sleep(1000);
this.Invoke(invoker);
}
else
{
if (done)
{
label1.Text = "Done";
}
else
{
label1.Text = "Progress: " + j.ToString();
(new Thread(invoker)).Start();
}
}
});
(new Thread(invoker)).Start();
for (int i = 0; i < 1000000000; i++)
{
j = (i * 3) / ((i * 3 == 0) ? 1 : i * 3) * i + i - i;
j = i;
}
done = true;
});
(new Thread(ts)).Start();
有更好的实现方法(例如Windows Forms计时器),但您明白了.
There are better ways of implementing that (e.g., a Windows Forms timer), but you get the idea.
这篇关于更新“快速更改"给用户的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!