将后台工作者传递给 VSTO Excel 加载项中的另一个 Class

Passing Background Worker to Another Class in a VSTO Excel Add In

我正在为 Excel 2010 构建一个 VSTO Excel 加载项...我有一个表单,用户可以选择一个查询,然后从 sheet 中适当地填充table。

我想在手术进行时报告进度。该操作存在于与 UI 不同的 class 中。因此,我构建了 class(ol 和 ole)并在 DoWork 处理程序中调用该方法。

private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = (BackgroundWorker)sender;

        if (!_isExtended)
        {
            oneline ol = new oneline();
            ol.buildOneline(this._wheres,worker );
        }
        else
        {
            ExtendedOneline ole = new ExtendedOneline();
            ole.buildExtendedOneline(this._wheres,worker);
        }
        //worker.ReportProgress();
        e.Result = "COMPLETE!";
    }

    private void backgroundWorker3_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        this.progressBar1.Value = e.ProgressPercentage;

    }

    private void backgroundWorker3_WorkerCOmpleted(object sender, RunWorkerCompletedEventArgs e)
    {
        MessageBox.Show(e.Result.ToString());
        this.Close();
    }

然后在 class 中,特别是我使用的方法为 BackgroundWorker bw 设置了一个参数。这就是我传递给工人的方式。然后在适当的时候我打算通过调用 bw.ReportProgress(PercentComplete)

来更新进度
public void buildOneline(List<WhereStatement> wheres, BackgroundWorker bw)
{
    ....
    ....
    double count = joinedWells.Count;
    double i = 1;
    foreach (var well in joinedWells)
    {
        double PercentComplete = 100 * (i / count);
        bw.ReportProgress((int)PercentComplete);
        ....
        ....
        i++;
    }

此脚本运行成功,但是进度条根本没有改变...想法?

编辑

    // backgroundWorker3
    this.backgroundWorker3.WorkerReportsProgress = true;
    this.backgroundWorker3.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker3_ProgressChanged);
    this.backgroundWorker3.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker3_DoWork);

编辑 2

//progressBar1
this.progressBar1.Location = new System.Drawing.Point(10, 340);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(583, 20);
this.progressBar1.Step = 1;
this.progressBar1.TabIndex = 15;
this.progressBar1.Maximum = 100;
this.progressBar1.Minimum = 0;

错误 我现在看到了这个我以前没有看到的错误。

`'System.InvalidOperationException' 类型的未处理异常发生在 System.Windows.Forms.dll

附加信息:跨线程操作无效:控件 'progressBar1' 从创建它的线程以外的线程访问。`

VSTO 的 BackgroundWorker 组件存在问题。您需要设置同步上下文才能使其正常工作。

System.Threading.SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());

bw = new BackgroundWorker();
...
bw.RunWorkerAsync();