[英]Is it possible to start background workers sequentially?
I want to use 3 background workers in sequential order.我想按顺序使用 3 个后台工作人员。
First one should do a job, update UI and start the second background worker which does the same and then starts the last one.第一个应该做一个工作,更新 UI 并启动第二个后台工作程序,它做同样的事情,然后启动最后一个。 This should repeat only when a button is clicked again.
这应该仅在再次单击按钮时重复。 Is such behavior possible to obtain?
这种行为有可能获得吗?
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
The reason for the background worker is not clear.后台工作者的原因尚不清楚。
However, you could do the following (assuming there is no legitimate async
IO work , and these tasks don't need to be run from a non threadpool thread ).但是,您可以执行以下操作(假设没有合法的
async
IO 工作,并且这些任务不需要从非线程池线程运行)。
Note : If there was legitimate async
IO work, you wouldn't need to wrap/offload to a Task
and would just use await
)注意:如果有合法的
async
IO 工作,则不需要包装/卸载到Task
,只需使用await
)
The advantages are :优点是:
Example例子
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
}
}
Note : Because this is an event
and async void
is appropriate, you need to make sure you deal with your exceptions (as this is unobserved).注意:因为这是一个
event
并且async void
是合适的,所以您需要确保处理您的异常(因为这是未观察到的)。 You might also want to guard against double clicks.您可能还想防止双击。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.