要求: 允许用户导入多个记录并允许单击多个导入按钮(在DATAGRID中)。
当用户点击单个导入按钮时,我能够处理导入按钮功能,但是如果用户点击另一个导入按钮,我就无法导入。
以下是我的代码。
BackgroundWorker bgWorkerUpdate = new BackgroundWorker();
// Constructor
public ImportedKeywords()
{
bgWorkerUpdate.DoWork += new DoWorkEventHandler(bgWorkerUpdateDoWork);
bgWorkerUpdate.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorkerUpdate_Completed);
}
private void Import_Click(object sender, RoutedEventArgs e)
{
if (!bgWorkerUpdate.IsBusy) bgWorkerUpdate.RunWorkerAsync(objSearchRequest);
else
{
bgWorkerUpdate = new BackgroundWorker();
bgWorkerUpdate.RunWorkerAsync(objSearchRequest);
}
}
public void bgWorkerUpdateDoWork(object sender, DoWorkEventArgs e)
{
SearchRequest objSearchRequest = (SearchRequest)e.Argument;//txtUserName.Text;
importCount = new AdvancedSearching().SearchContent(objSearchRequest, totalRecords, totalRecordsImported, recordsToImport, keywordID, selectedPriority);
}
void bgWorkerUpdate_Completed(object sender, RunWorkerCompletedEventArgs e)
{
imgLoading.Visibility = System.Windows.Visibility.Hidden;
if (importCount == 0)
{
lblMessage.Content = "No record found to import.";
lblMessage.Foreground = Brushes.DarkRed;
}
else
{
lblMessage.Content = importCount + " Record(s) imported successfully.";
lblMessage.Foreground = Brushes.DarkGreen;
BindList(Convert.ToInt32(tbStartPage.Text), txtSearch.Text, "test");
MaintainSortingWithPaging(Convert.ToInt32(tbStartPage.Text));
}
HideLoading();
}
答案 0 :(得分:1)
当您创建BackgroundWorker
的新实例时,您必须再次订阅DoWork
和RunWorkerCompleted
个事件。否则,当你运行它时它什么也没做。
if (!bgWorkerUpdate.IsBusy)
bgWorkerUpdate.RunWorkerAsync(objSearchRequest);
else
{
bgWorkerUpdate = new BackgroundWorker();
bgWorkerUpdate.DoWork += bgWorkerUpdateDoWork;
bgWorkerUpdate.RunWorkerCompleted+= bgWorkerUpdate_Completed;
bgWorkerUpdate.RunWorkerAsync(objSearchRequest);
}
但是,如果您想要做的就是在新线程中运行每个作业(如果旧作业仍在运行),也许您可以研究其他构造,例如Task.Run
。