Reputation: 1
What would be the most optimal solution here? I would like to use this variable to indicate the progress of the simulations.
EDIT: added the ALMBerekeningen code. This is just a small part of it, the full code is too much to show here.
Thanks!
public class ALMBerekeningen
{
public int sim;
public int Progress;
public double ProgressPerc;
this.ProgressPerc = this.sim / 1000;
this.Progress = (int)Math.Round(this.Progress * 100f, 0, MidpointRounding.AwayFromZero);
}
Public class Form1: Form
{
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
ALMBerekeningen ProgressPerc;
int sims;
sims = (int)ProgressPerc;
try
{
backgroundWorker1.ReportProgress(sims);
}
catch (Exception ex)
{
backgroundWorker1.CancelAsync();
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
lblProgress.Text = "Completed " + progressBar1.Value.ToString() + " %";
progressBar1.Update();
}
}
Upvotes: 0
Views: 439
Reputation: 11216
You need to pass in the instance of ALMBerekeningen
to the background worker when you start it and then access it using the DoWorkEventArgs.Argument
property in the event handler:
public void Main()
{
//The instance of the class with the variable for your progress bar
ALMBerekeningen almBerekeningen = new ALMBerekeningen();
BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += bgw_DoWork;
//Pass your class instance in here
bgw.RunWorkerAsync(almBerekeningen);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//e.Argument is the instance of the class you passed in
var progressPerc = (ALMBerekeningen)e.Argument;
int sims;
sims = progressPerc.ProgressPerc;
try
{
backgroundWorker1.ReportProgress(sims);
}
catch (Exception ex)
{
backgroundWorker1.CancelAsync();
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Incidentally, your DoWork
handler as shown will only execute one time. I presume that you have just simplified it down for the sake of the example.
Upvotes: 1