我需要调用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'。
答案 0 :(得分:2)
您可以使用lambda作为DoWork
事件处理程序来关闭变量(注意闭包关闭变量,而不是值,因此这不会只复制值)。从那里你可以在lambda中做正确的工作,或者通过引用将变量传递给其他方法。
int someValue = 5;
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (s, args) =>
{
ProcessValue(ref someValue);
};
worker.RunWorkerAsync();
答案 1 :(得分:-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;
}
}