【发布时间】:2018-03-20 18:29:54
【问题描述】:
以下是我正在处理的一个类的精简版(WinForms 项目的一部分):
class ReportBuilder {
private List<Project> projects;
private List<Invoice> invoices;
private MyAPI apiObject;
public ReportBuilder(MyAPI apiAccess, List<Project> selectedProjects){
this.apiObject = apiAccess;
this.projects = selectedProjects;
}
public void DownloadData(){
BackgroundWorker workerThread = new BackgroundWorker();
workerThread.DoWork += (sender, e) => this.retrieveInvoices(this.projects); // yes, the parameter is unnecessary in this case, since the variable is in scope for the method anyway, but I'm doing it for illustrative purposes
workerThread.RunWorkerCompleted += receiveData;
workerThread.RunWorkerAsync();
}
private void retrieveInvoices(List<Project> filterProjects){
Notification status;
if (filterProjects == null){this.invoices = this.apiObject.GetInvoices(out status);}
else {this.invoices = this.apiObject.GetInvoices(filterProjects, out status);}
}
private void receiveData(Object sender, RunWorkerCompletedEventArgs e){
// display a save file dialog to the user
// call a method in another class to create a report in csv format
// save that csv to file
// ... ideally, this method would to have access to the 'status' Notification object from retrieveInvoices, but it doesn't (unless I make that an instance variable)
}
}
现在,DoWork 事件处理程序的方法签名通常是这样的:
private void retrieveInvoices(object sender, DoWorkEventArgs e)
但是,正如您在上面看到的,我的retrieveInvoices 方法的签名与该签名不匹配。因此,我预计它会失败(要么不编译,要么只是在 UI 线程上运行 retrieveInvoices,阻止它,而不是在后台工作人员中)。令我惊讶的是,它似乎正在工作,但由于我所见过的 BackgroundWorker 示例都没有这样做,所以我仍然认为我一定做错了什么。但我是吗,为什么?
【问题讨论】:
-
是的,它确实与此匹配:
(sender, e) => -
您可以将
e传递给您的retrieveInvoices() 方法。
标签: c# backgroundworker