如何从 backgroundWorker 以及百分比向我的 windows.form 报告字符串(如“正在搜索文件......”,“找到的选择......”)。此外,我有一个大类,其中包含我想在 backgroundWorker_Work 中运行的方法。我可以通过 Class_method() 调用它;但我无法报告我完成的百分比或来自被调用类的任何内容,只能来自 backgroundWorker_Work 方法。
谢谢!
如何从 backgroundWorker 以及百分比向我的 windows.form 报告字符串(如“正在搜索文件......”,“找到的选择......”)。此外,我有一个大类,其中包含我想在 backgroundWorker_Work 中运行的方法。我可以通过 Class_method() 调用它;但我无法报告我完成的百分比或来自被调用类的任何内容,只能来自 backgroundWorker_Work 方法。
谢谢!
我假设WCF也有这个方法
public void ReportProgress(int percentProgress, Object userState);
所以只需使用 userState 来报告字符串。
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
//report some progress
e.ReportProgress(0,"Initiating countdown");
// initate the countdown.
}
你会在 ProgressChanged 事件中得到那个“启动倒计时”字符串
private void worker_ProgressChanged(object sender,ProgressChangedEventArgs e)
{
statusLabel.Text = e.UserState as String;
}
您可以使用ReportProgress
方法的 userState 参数来报告该字符串。
这是来自 MSDN 的示例:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// This method will run on a thread other than the UI thread.
// Be sure not to manipulate any Windows Forms controls created
// on the UI thread from this method.
backgroundWorker.ReportProgress(0, "Working...");
Decimal lastlast = 0;
Decimal last = 1;
Decimal current;
if (requestedCount >= 1)
{ AppendNumber(0); }
if (requestedCount >= 2)
{ AppendNumber(1); }
for (int i = 2; i < requestedCount; ++i)
{
// Calculate the number.
checked { current = lastlast + last; }
// Introduce some delay to simulate a more complicated calculation.
System.Threading.Thread.Sleep(100);
AppendNumber(current);
backgroundWorker.ReportProgress((100 * i) / requestedCount, "Working...");
// Get ready for the next iteration.
lastlast = last;
last = current;
}
backgroundWorker.ReportProgress(100, "Complete!");
}
这是一个由 3 部分组成的系列。
使用委托。