使用BackgroundWorker在WPF的数据网格中使用多个导入按钮导入多个记录
本文关键字:导入 记录 按钮 网格 BackgroundWorker WPF 数据网 数据 使用 | 更新日期: 2023-09-27 18:15:40
要求:允许用户导入多个记录,并允许点击多个导入按钮(在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();
}
当您创建一个新的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
。