我想按顺序使用3个后台工作人员。
第一个应该做一个工作,更新UI并启动第二个后台工作人员,然后启动最后一个工作。仅在再次单击按钮时才会重复此操作。这种行为有可能获得吗?
public Form1()
{
InitializeComponent();
Bw1= = new BackgroundWorker();
Bw2= = new BackgroundWorker();
Bw3= = new BackgroundWorker();
Bw1.DoWork += new DoWorkEventHandler(Bw1_DoWork);
Bw1.ProgressChanged += new ProgressChangedEventHandler
(Bw1_ProgressChanged);
Bw1.RunWorkerCompleted += new RunWorkerCompletedEventHandler
(Bw1_RunWorkerCompleted);
Bw1.WorkerReportsProgress = true;
Bw1.WorkerSupportsCancellation = true;
...
Bw3.DoWork += new DoWorkEventHandler(Bw3_DoWork);
Bw3.ProgressChanged += new ProgressChangedEventHandler
(Bw3_ProgressChanged);
Bw3.RunWorkerCompleted += new RunWorkerCompletedEventHandler
(Bw3_RunWorkerCompleted);
Bw3.WorkerReportsProgress = true;
Bw3.WorkerSupportsCancellation = true;
}
private void btnStartAsyncOperation_Click(object sender, EventArgs e)
{
btnStartAsyncOperation.Enabled = false;
btnCancel.Enabled = true;
// Kickoff the worker thread to begin its DoWork function.
BW1.RunWorkerAsync();
}
//THE DO WORK PART
//UPDATE UI
//tHEN
void BW1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
STOP BW1;
BW2.RUN();
}
...
//Until BW 3 completes and here this should stop until next click
背景工作者的原因尚不清楚。
但是,您可以执行以下操作(假设没有合法的async
IO工作,并且这些任务不需要从非线程池线程运行)。
注意:如果有合法的async
IO工作,你不需要包装/卸载到Task
并只使用await
)
优点是:
例
private async void btnStartAsyncOperation_Click(object sender, EventArgs e)
{
try
{
await Task.Run(() => FirstTask1());
// update the ui
await Task.Run(() => FirstTask2());
// update the ui
await Task.Run(() => FirstTask3());
// update the ui
}
catch (Exception exception)
{
// make sure you catch or do something with exception
}
}
注意:因为这是一个event
和async void
是合适的,你需要确保你处理你的异常(因为这是未观察到的)。您可能还希望防止双击