-2

我需要调用一个 C dll 作为后台进程。dll 的执行很耗时,因此我想在主 GUI 上显示一个进度条。为了使用 ReportProgress,我需要能够通过引用传递两个参数,并在参数值发生变化时更新进度条。但是, RunWorkerAsync 似乎只接受值(而不是引用)。

我该怎么做?

谢谢。

这是简化的代码:

public void button1_Click(object sender, EventArgs e)
    {
       //Variable declarations and initializations

       List<object> arguments = new List<object>();
                arguments.Add(curgen);
                arguments.Add(dataindex);

        backgroundWorker1.RunWorkerAsync(arguments);
        backgroundWorker1.ReportProgress(curgen * 100 / ngen, "GEN");
        backgroundWorker1.ReportProgress(dataindex * 100 / (DIMENSION * FITNESSCASES), "DATA");

    }

 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        List<object> genericlist = e.Argument as List<object>;
        // Getting variables from object
         calldll.gpinnovization(ref curgen, ref dataindex);
    }

我想通过引用传递“curgen”和“dataindex”。

4

2 回答 2

2

您可以为事件处理程序使用 lambdaDoWork来关闭变量(请注意,闭包关闭变量,而不是值,因此这不会只是复制值)。从那里您可以在 lambda 中直接完成工作,或者通过引用将变量传递给其他方法。

int someValue = 5;

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (s, args) =>
{
    ProcessValue(ref someValue);
};
worker.RunWorkerAsync();
于 2013-04-05T16:24:05.223 回答
-2

为了他人的利益,这就是我最终做到的方式。感谢 Servy 建议 lambda 表达式:

        BackgroundWorker backgroundWorker1 = new BackgroundWorker();
        backgroundWorker1.WorkerReportsProgress = true;
        backgroundWorker1.DoWork += (s, args) =>
            {
                Mydll.MyCfunction(ref curgen, ref dataindex);
            };
        backgroundWorker1.RunWorkerAsync();
        backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;


        while (backgroundWorker1.IsBusy)
        {
            backgroundWorker1.ReportProgress(curgen * 100 / ngen, "GEN");
            backgroundWorker1.ReportProgress(dataindex * 100 / (DIMENSION * FITNESSCASES), "DATA");
            Application.DoEvents();
        }

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e1)
    {
        switch (e1.UserState.ToString())
        {
            case "GEN":
                progressBar1.Value = e1.ProgressPercentage;
                break;
            case "DATA":
                progressBar2.Value = e1.ProgressPercentage;
                break;
        }

    }
于 2013-04-08T09:30:58.747 回答