这里最好的解决方案是什么?我想用这个变量来指示模拟的进度。
编辑:添加了 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();
}
}
最佳答案
你需要传入ALMBerekeningen
的实例当您启动它时到后台工作人员,然后使用 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
如图所示的处理程序只会执行一次。我认为您只是为了示例而将其简化了。
关于c# - 在两个不同的类之间使用后台 worker 的进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45330669/