[英]Progress Bar using Background worker between two different classes
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. 编辑:添加了ALMBerekeningen代码。 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();
}
}
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: 您需要在启动时将ALMBerekeningen
实例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);
}
}
Incidentally, your DoWork
handler as shown will only execute one time. 附带地,您显示的DoWork
处理程序将只执行一次。 I presume that you have just simplified it down for the sake of the example. 我认为您只是为了示例而将其简化了下来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.