合并两个背景工人完成时的结果 [英] Merging the results of two background workers upon completion

查看:145
本文介绍了合并两个背景工人完成时的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个后台线程

Worker = new BackgroundWorker();
Worker.DoWork += new DoWorkEventHandler(GetQuery);
Worker.RunWorkerCompleted += GetQuery_RunWorkerCompleted;
Worker.RunWorkerAsync();

Worker2012 = new BackgroundWorker();
Worker2012.DoWork += new DoWorkEventHandler(GetQuery2012);
Worker2012.RunWorkerCompleted += GetQuery2012_RunWorkerCompleted;
Worker2012.RunWorkerAsync();

无论是在工作线程的方法返回数据表

both the methods in worker threads are returning data tables

现在我的任务是我需要这两个数据表合并成一个

now my task is i need to merge those two data tables into one

对于这个原因,我第一个任务中的RunCompletion这样

for that reason i am doing this in the RunCompletion of the first task

void GetQuerys_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
   do{} while(Worker2012.IsBusy);
   //Merge Datatables
}

但由于某种原因而循环似乎是无限循环的做。该线程并没有结束。可有一个人告诉我,我做错了。还是有更好的方式来等待第二个工作线程,以便获得完整,这样我可以合并数据。任何帮助将是AP preciated

but for some reason the do while loop seems to be in infinite loop. the thread does not end. can some one tell me what i am doing wrong. or is there a better way to wait for the second worker thread to get complete so that i can merge data. any help would be appreciated

推荐答案

现在的.NET 4.5已经出来了,我建议大家使用 Task.Run 而不是的BackgroundWorker ,因为这样的:

Now that .NET 4.5 is out, I recommend that everyone use Task.Run instead of BackgroundWorker, as such:

var task1 = Task.Run(() => GetQuery());
var task2 = Task.Run(() => GetQuery2012());
var dataTables = await Task.WhenAll(task1, task2);
// Merge databases

Task.Run 优于的BackgroundWorker 以各种方式,这是做任何事情的时候复杂尤为明显(即,协调两个后台操作)。

Task.Run is superior to BackgroundWorker in every way, and this is particularly noticeable when doing anything complex (i.e., coordinating two background operations).

这篇关于合并两个背景工人完成时的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆