在我的.NET C#项目中,我使用“BackgroundWorker”来调用另一个类中的方法。以下是我的主要表格的源代码
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
testClass t1 = new testClass();
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
t1.changevalue(1000);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Text += Convert.ToString(e.ProgressPercentage);
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
}
并在我的项目中名为“testClass.cs”的单独类文件中包含以下代码。我想从此类向BackgroundWorker报告进度,以便我能够从label1显示main中的进度。
class testClass
{
private int val;
public int changevalue(int i)
{
for (int j = 0; j < 1000; j++)
{
val += i + j;
//from here i need to preport the backgroundworker progress
//eg; backgroundworker1.reportProgress(j);
}
return val;
}
}
但我不允许从“testClass”访问BackgroundWorker。
有人可以告诉我们如何克服这个问题吗?
p.s-我找到了this solution,但我不明白。
答案 0 :(得分:29)
您可以将其作为变量传递
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
t1.changevalue(1000, sender as BackgroundWorker);
}
class testClass
{
private int val;
public int changevalue(int i, BackgroundWorker bw)
{
for (int j = 0; j < 1000; j++)
{
val += i + j;
bw.ReportProgress(i);
//from here i need to preport the backgroundworker progress
//eg; backgroundworker1.reportProgress(j);
}
return val;
}
}
但是我认为最好的选择是event
testClass
可以Form
分配给public partial class Form1 : Form
{
private BackgroundWorker backgroundWorker1;
private testClass t1 = new testClass();
public Form1()
{
InitializeComponent();
// subscribe to your event
t1.OnProgressUpdate += t1_OnProgressUpdate;
}
private void t1_OnProgressUpdate(int value)
{
// Its another thread so invoke back to UI thread
base.Invoke((Action)delegate
{
label1.Text += Convert.ToString(value);
});
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
t1.changevalue(1000);
}
private void button1_Click_1(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
}
class testClass
{
public delegate void ProgressUpdate(int value);
public event ProgressUpdate OnProgressUpdate;
private int val;
public int changevalue(int i)
{
for (int j = 0; j < 1000; j++)
{
val += i + j;
// Fire the event
if (OnProgressUpdate != null)
{
OnProgressUpdate(i);
}
}
return val;
}
}
。
{{1}}
答案 1 :(得分:1)
我刚刚遇到同样的问题(我的长时间运行过程是数据库恢复),并通过在另一个类中引发事件以类似的方式解决了这个问题,但随后让我的订阅者参加了该事件作为backgroundWorker1.ReportProgress()的包装器。
private void DBRestoreProgressHandler(DataAccess da, DataAccess.DatabaseRestoreEventArgs e)
{
backgroundWorker1.ReportProgress(e.RestoreProgress);
}
private void backgroundWorker1_ReportProgress(object sender, ProgressChangedEventArgs e)
{
someLabel.Text = e.ProgressPercentage.ToString();
}
这节省了必须使用:
base.Invoke((Action)delegate
如果表单意外关闭,我认为可能会导致问题?
答案 2 :(得分:-2)
我在上面的代码中错过了吗?:
backgroundWorker1 = new BackgroundWorker();
backgroundWorker1.DoWork + =新的DoWorkEventHandler(backgroundWorker1_DoWork);