我如何从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事件中获得"Initiating countdown"字符串。
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!");
}
使用委托。