【问题标题】:Need help on Backgroundworker在 Backgroundworker 上需要帮助
【发布时间】:2010-09-02 09:54:18
【问题描述】:

*注意:根据用户的 cmets 重新表述我的问题。

需要有关如何将 .Net 的 Backgroundworker 线程用于以下目的的帮助,以提高我的 .Net winforms 应用程序中的 UI 响应能力和性能。 当用户单击 UI 表单中的“计算”按钮时,我正在这样做:

1.从数据库中获取类别C的列表[这通常在10个左右]

2.对于每个类别C,执行以下操作:

a.调用第三方库,做一些处理,计算分类价格。

b.获取产品列表[这通常是 800 左右]。

c.对于每个产品,使用上面的类别价格计算其价格。

d.使用存储过程将每个产品的价格更新回数据库中。

3.将进度更新回[或报告任何错误消息]到 UI 中的表单。

仅供参考,我想在上面的步骤 #c 和 #d 中使用 Backgroundworker。

我尝试在我的方法中使用 Backgroundworker。我将调用 InitializeBackgroundworker() 和 RunWorkerAsync() 放在最外层循环中[即。第 2 步]。但是看起来,Backgroundworker 仅被第一个类别调用。我在这里缺少什么?

所以我的问题是,我在哪里调用 InitializeBackgroundworker() 和 RunWorkerAsync()? 以及如何确保为每个类别调用这两种方法?

感谢阅读。

【问题讨论】:

  • 我能想到几个地方看看——你能把主循环的代码贴出来吗?

标签: c# multithreading backgroundworker


【解决方案1】:

尝试这样的事情作为开始。

BackgroundWorker worker = new BackgroundWorker();

void SomeForm_Load(object sender, EventArgs e)
{
  // setup the BackgroundWorker 
  worker.WorkerReportsProgress = true;
  worker.DoWork += new DoWorkEventHandler(worker_DoWork);
  worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
  worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_Completed);
}

void SomeControl_Click(object sender, EventArgs e)
  List<Category> categories = DataBase.GetSomeCategories(); // [1] get Category list
  // start the BackgroundWorker passing in the categories list.
  worker.RunWorkerAsync(categories);
}

void worker_DoWork(object sender, DoWorkEventArgs e)
{
  int progress = 0;
  var categories = e.Argument as List<Category>;       
  categories.ForEach(category =>                         // [2] process each Category
  {
    ThirdPartyControl.DoSomeProcessing(category);        // [2.a]
    var categoryPrice = CalculateCategoryPrice(category);
    var products = GetListOfProducts(category);          // [2.b] 
    products.ForEach(product =>                          // [2.c] process each Product
    {          
      var productPrice = CalcProductPrice(categoryPrice); 
      DataBase.UpdateProduct(product, productPrice);     // [2.d]
      progress = //...calculate progress...
      worker.ReportProgress(progress);                   // [3]
    });
    progress = //...calculate progress...
    worker.ReportProgress(progress);                     // [3]
  });
  worker.ReportProgress(100);
}

void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
  //...update some UI stuff...
  progressBar.Value = e.ProgressPercentage;
}

void worker_Completed(object sender, RunWorkerCompletedEventArgs e)
{
  //...all done...
}

随着理解的加深,您总是可以将其分解为多个 BackgroundWorker。

【讨论】:

    【解决方案2】:
    猜你喜欢
    • 2011-07-10
    • 2011-06-23
    • 2014-11-04
    • 1970-01-01
    • 2022-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多