有没有办法让后台工作人员排队。
场景:我们有两个BackgroundWorker对象,BGW1& BGW2。
我可以按顺序运行它们,比如说BGW1正在运行且事件是否调用BGW2。我可以用BGW1排队吗?同样,如果BGW1完成了它的运行;并且BGW2正在运行我应该能够排队BGW1并等到BGW2完成其运行。
答案 0 :(得分:0)
如果他们必须互相追逐,可以使用RunWorkerCompleted
事件开始下一个事件,反之亦然。可以使用if子句来终止循环调用。
这是一个可以实现这一目标的课程:
public class BGWQue
{
public BackgroundWorker Worker_1 { get; set; }
public BackgroundWorker Worker_2 { get; set; }
bool endWorkerLoop = false;
public BGWQue()
{
this.Worker_1 = new BackgroundWorker();
this.Worker_1.DoWork += Worker_1_DoWork;
this.Worker_1.RunWorkerCompleted += Worker_1_RunWorkerCompleted;
this.Worker_2 = new BackgroundWorker();
this.Worker_2.DoWork += Worker_2_DoWork;
this.Worker_2.RunWorkerCompleted += Worker_2_RunWorkerCompleted;
}
void Worker_1_DoWork(object sender, DoWorkEventArgs e)
{
job_1();
}
void Worker_1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// condition to end the cycle
if (!endWorkerLoop)
{
this.Worker_2.RunWorkerAsync();
}
}
void Worker_2_DoWork(object sender, DoWorkEventArgs e)
{
job_2();
}
void Worker_2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// condition to end the cycle
if (!endWorkerLoop)
{
this.Worker_1.RunWorkerAsync();
}
}
public void startWorkers()
{
this.Worker_1.RunWorkerAsync();
}
// fictional jobs for the workers
public void job_1()
{
Thread.Sleep(2000);
}
public void job_2()
{
Thread.Sleep(3000);
}
}