您只能从UI线程(WinForm线程)设置进度条用户控件属性。使用BackgroundWorker最简单的方法是使用ProgressChanged事件:
private BackgroundWorker bwForm;
private ProgressBar progressBar;
在WinForm构造函数中:
this.progressBar = new ProgressBar();
this.progressBar.Maximum = 100;
this.bwForm = new BackgroundWorker();
this.bwForm.DoWork += new DoWorkEventHandler(this.BwForm_DoWork);
this.bwForm.ProgressChanged += new ProgressChangedEventHandler(this.BwForm_ProgressChanged);
this.bwForm.RunWorkerAsync();
...
void BwForm_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bgw = sender as BackgroundWorker;
int percent = 0;
bgw.ReportProgress(percent);
}
void BwForm_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar.Value = e.ProgressPercentage;
}
请看这里:
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
编辑:
我之前误解了你的问题,我以为它是关于在工作期间显示进度条进度的。如果它是关于工作结果,请在BwForm_DoWork事件中使用e.Result。添加一个完成事件处理程序并管理结果即可。
this.bwForm.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.BwForm_RunWorkerCompleted);
...
private void BwForm_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
YourResultStruct result = e.Result as YourResultStruct;
if (e.Error != null && result != null)
{
}
}
Invoke
或者DoWork
的代码。你必须向我们展示代码以便我们进行诊断。 - Dour High Arch