I have a few nested for loops, and I was wondering if I could get the data while it's processing it, So I can show it on the screen as a loading bar.
Here's an example:
double currentData;
double endData = 50 * 50 * 50;
for(int i = 0; i < 50; i++)
{
for(int e = 0; e < 50; e++)
{
for(int a = 0; a < 50; a++)
{
currentData = a * e * i;
}
}
}
label1.Text = "Loading: " + Convert.ToString(100/endData * currentData) + "%.";
If I'm not wrong, for loops make the program "freeze" until its done, so that's probably why this code won't work. Any suggestions?
Thanks
Well if you are using WinForms you can use background worker to execute the loop:
//declare in form
var bw = new BackgroundWorker();
//in constructor or load write this
bw.WorkerReportsProgress = true;
bw.DoWork += new DoWorkEventHandler(bwDoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bwProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwCompleted);
private void bwDoWork(object sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
for(int i = 0; i < 50; i++)
{
for(int e = 0; e < 50; e++)
{
for(int a : 0; a < 50; a++)
{
worker.ReportProgress(a * e * i);
}
}
}
}
private void bwProgressChanged(object sender, ProgressChangedEventArgs e)
{
var pp=e.ProgressPercentage; //now set the progress here
}
private void bwCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//set the progress to 100% etc.
}
Then as pointed by @paqogomez you need to call the worker to run, may be on some button click etc.
//may be in private void button_click(object sender, EventArgs e)
if (!bw.IsBusy)
{
bw.RunWorkerAsync();
}
You can get more info on BackgroundWorker here and here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With