Your
ProgressBarTest
method never relinquishes control. The UI thread is blocked until the method returns, which is why you only ever see the final value, not the intermediate values.
If you want to use a
BackgroundWorker
, then you need to do the work in the
DoWork
event handler:
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
lblProg.Text = "Current progress: " + e.ProgressPercentage + "%";
}
If you want to use a timer, then you need to do the work in a background thread, or in a manner that yields control to the UI thread. The simplest option would probably be an
async
method:
public static async Task ProgressBarTestAsync()
{
for (int i = 0; i < 100; i++)
{
await Task.Delay(100);
TestSettings.ProgressValue = i;
}
}
...
private async void button1_Click(object sender, EventArgs e)
{
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
progressBar1.Value = 0;
progressBar1.Enabled = true;
timer1.Enabled = true;
await RetirementPlan.MainMethods.ProgressBarTestAsync();
timer1.Enabled = false;
progressBar1.Value = 0;
progressBar1.Enabled = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
progressBar1.Value = RetirementPlan.Utils.TestSettings.ProgressValue;
double percentage = ((double)progressBar1.Value / (double)progressBar1.Maximum) * 100;
lblProg.Text = "Current progress: " + percentage + "%";
}