这里最优的解决方案是什么?我想用这个变量来表示模拟的进度。
编辑:添加了ALMBerekeningen代码。这只是其中的一小部分,完整的代码太多了,不能在这里显示。
谢谢!
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();
}
}
答案 0 :(得分:1)
启动它时,需要将ALMBerekeningen
的实例传递给后台worker,然后使用事件处理程序中的DoWorkEventArgs.Argument
属性访问它:
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);
}
}
顺便提一下,您显示的DoWork
处理程序只会执行一次。我认为你为了这个例子而简化了它。