使用BackgroundWorker在WPF中使用数据网格中的多个导入按钮导入多个记录

时间:2014-07-31 04:44:41

标签: c# wpf datagrid backgroundworker

要求: 允许用户导入多个记录并允许单击多个导入按钮(在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();
        }

1 个答案:

答案 0 :(得分:1)

当您创建BackgroundWorker的新实例时,您必须再次订阅DoWorkRunWorkerCompleted个事件。否则,当你运行它时它什么也没做。

if (!bgWorkerUpdate.IsBusy)
    bgWorkerUpdate.RunWorkerAsync(objSearchRequest);
else
{
    bgWorkerUpdate = new BackgroundWorker();
    bgWorkerUpdate.DoWork += bgWorkerUpdateDoWork;
    bgWorkerUpdate.RunWorkerCompleted+= bgWorkerUpdate_Completed;
    bgWorkerUpdate.RunWorkerAsync(objSearchRequest);
}

但是,如果您想要做的就是在新线程中运行每个作业(如果旧作业仍在运行),也许您可​​以研究其他构造,例如Task.Run