How to start BackgroundWorker after CancelAsync
I'm using backgroundworker in UserControls which I'm loading into panels by a button click. I hit CancelAsync BW in one UC, then I go to another UC. When I want to return to previous UС (where I've canceled BW) I always enter RunWorkerCompleted event.
I've tried to re-initialize BW in UC constructor:
bgrWorker = new BackgroundWorker
{
WorkerSupportsCancellation = true,
WorkerReportsProgress = true
};
bgrWorker.DoWork += DoWork;
bgrWorker.ProgressChanged += ProgressChanged;
bgrWorker.RunWorkerCompleted += RunWorkerCompleted;
btnStop.Click += StopWorker;
But it doesn't work.
Code of DoWork event:
System.Threading.Tasks.Parallel.For(0, _list.Count, num =>
{
开发者_JS百科 if (bgrWorker.CancellationPending)
{
e.Cancel = true;
}
else
{
_splittedList.Add(FindMiddle.Find(_list[num], 20));
bgrWorker.ReportProgress(0);
}
});
(As instructed in comments :)
When you return to the previous user control, that won't rerun the constructor - so if you need to reinitialize the BackgroundWorker
at that point, you need to move the initialization code into a method that can be run at the appropriate time.
精彩评论