首页 新闻 会员 周边 捐助

关于BackgroundWorker多线程同步问题,多个BackgroundWorker调用同一个DoWorker函数

0
悬赏园豆:5 [已关闭问题] 关闭于 2016-04-24 18:24

定义了一组 List bgws = new List();其中每一个bgws[i]的DoWork事件做的工作都是一样的,但是有一个参数随每个bgws[i]不同而不同,所以就如下分别写了很多DoWork0、DoWork1.。。。之类的来进行同步处理,有没有更简洁的办法,可以同时调用进行使用?
private void btnCopy_Click(object sender, EventArgs e)
{
for (int i = 0; i < srctable.Count; i++)
{
BackgroundWorker bgw = new BackgroundWorker();
bgws.Add(bgw);
bgws[i].WorkerReportsProgress = true;
bgws[i].WorkerSupportsCancellation = true;
//bgws[i].DoWork += new DoWorkEventHandler(DoWork);
//bgws[i].ProgressChanged += new ProgressChangedEventHandler(UpdateProgress);
//bgws[i].RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork);
}
string[,] tName = new string[srctable.Count, 2];


        bgws[0].DoWork += new DoWorkEventHandler(DoWork0);
        bgws[0].ProgressChanged += new ProgressChangedEventHandler(UpdateProgress0);
        bgws[0].RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork0);

        bgws[1].DoWork += new DoWorkEventHandler(DoWork1);
        bgws[1].ProgressChanged += new ProgressChangedEventHandler(UpdateProgress1);
        bgws[1].RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork1);

        bgws[2].DoWork += new DoWorkEventHandler(DoWork2);
        bgws[2].ProgressChanged += new ProgressChangedEventHandler(UpdateProgress2);
        bgws[2].RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork2);

        bgws[3].DoWork += new DoWorkEventHandler(DoWork3);
        bgws[3].ProgressChanged += new ProgressChangedEventHandler(UpdateProgress3);
        bgws[3].RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork3);


        bgws[0].RunWorkerAsync();
        bgws[1].RunWorkerAsync();
        bgws[2].RunWorkerAsync();
        bgws[3].RunWorkerAsync();         
    }
一碗周的主页 一碗周 | 菜鸟二级 | 园豆:203
提问于:2016-04-18 17:59
< >
分享
所有回答(3)
0

bgws[i].RunWorkerAsync(bgws[i])

然后你的DoWork方法就可以接受到bgws[i]

jello chen | 园豆:7336 (大侠五级) | 2016-04-18 21:44
0

如果这个参数只是不同而已,而不影响DoWork,可以写个方法,通过i加lock来获取这个参数

Yu | 园豆:12990 (专家六级) | 2016-04-19 10:54

我现在改成定义局部变量来获得参数tName[2],然后执行bgws[i].RunWorkerAsync(tName);现在每个bgws[i]的ReportProgress(a)里的a也随之不同,我想要获得每个bgws[i]的进度该怎么办啊?

for (int i = 0; i < srctable.Count; i++)
{
BackgroundWorker bgw = new BackgroundWorker();
bgws.Add(bgw);
string[] tName = new string[2];
tName[0] = srctable[i];
tName[1] = destable[i];

bgws[i].WorkerReportsProgress = true;
bgws[i].WorkerSupportsCancellation = true;
bgws[i].DoWork += new DoWorkEventHandler(DoWork);
bgws[i].ProgressChanged += new ProgressChangedEventHandler(UpdateProgress);
bgws[i].RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWorke);

bgws[i].RunWorkerAsync(tName);
}

支持(0) 反对(0) 一碗周 | 园豆:203 (菜鸟二级) | 2016-04-19 11:20

@Avanti: 凭空想象不出

支持(0) 反对(0) Yu | 园豆:12990 (专家六级) | 2016-04-19 11:33
0

自定义类,通过声明不同的类的对象来调用公用的类的方法与字段

一碗周 | 园豆:203 (菜鸟二级) | 2016-04-24 18:24
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册