定义了一组 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();
}
bgws[i].RunWorkerAsync(bgws[i])
然后你的DoWork方法就可以接受到bgws[i]
如果这个参数只是不同而已,而不影响DoWork,可以写个方法,通过i加lock来获取这个参数
我现在改成定义局部变量来获得参数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);
}
@Avanti: 凭空想象不出
自定义类,通过声明不同的类的对象来调用公用的类的方法与字段