使用BackgroundWorker取消时遇到问题,它只能使用一次。
第二次进入结束活动。
取消后我需要使用:backgroundWorker.Dispose()吗?
这是我的代码:
master
感谢您的帮助。
答案 0 :(得分:2)
BackgroundWorker
完成后,无法重新启动。在其上调用Dispose()
是您应该做的事情,但它不允许您重新启动它。
您需要创建新的BackgroundWorker
或使用更现代的async
样式编程(如果您使用.Net 4.5或更高版本)。
答案 1 :(得分:0)
@Matthew Watson回答的一些修正。
BackgroundWorker
完成后, CAN 重新启动,您只需要正确执行即可。我做过很多次,而且总是有效。
(在某些情况下,一遍又一遍地创建新的BackgroundWorkers
是可取的,但要小心处理所使用的资源。如果你一次启动多个工人,你也应该注意的局限性线程池,以及执行操作,例如从多个线程同时对驱动器上的文件执行操作,实际上可能会降低您的应用程序速度)
多次演示使用相同BackgroundWorker的工作代码:
BackgroundWorker bg;
....
// Constructor: create the worker (once):
bg = new BackgroundWorker();
bg.WorkerSupportsCancellation = true;
bg.DoWork += new DoWorkEventHandler(bg_DoWork);
bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
private void btnStartBgw_Click(object sender, EventArgs e)
{
if (!bg.IsBusy)
bg.RunWorkerAsync();
else MessageBox.Show("The worker thread is busy!");
}
void bg_DoWork(object sender, DoWorkEventArgs e)
{
this.DoWorkImpl((BackgroundWorker)sender, e);
}
private void DoWorkImpl(BackgroundWorker backgroundWorker, DoWorkEventArgs e)
{
for(int i=0;i<30;i++)
{
Thread.Sleep(1000);
if (backgroundWorker.CancellationPending)
{
e.Cancel = true;
return;
}
}
}
void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("The work was canceled");
}
else
{
MessageBox.Show("The work was completed successfuly");
}
}
private void btnCancelBgw_Click(object sender, EventArgs e)
{
if (bg.IsBusy) bg.CancelAsync();
else MessageBox.Show("The worker thread is not running!");
}
另外,我认为您应该重新考虑从后台线程中抛出异常。相反,您可以在e.Result
中返回一些错误状态。
答案 2 :(得分:0)
BackgroundWorker _BackgroundWorker = new BackgroundWorker();
public Form1()
{
InitializeComponent();
_BackgroundWorker.DoWork += _BackgroundWorker_DoWork;
_BackgroundWorker.RunWorkerCompleted += _BackgroundWorker_RunWorkerCompleted;
_BackgroundWorker.ProgressChanged += _BackgroundWorker_ProgressChanged;
_BackgroundWorker.WorkerSupportsCancellation = true;
}
void _BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
throw new NotImplementedException();
}
void _BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
throw new NotImplementedException();
}
void _BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
throw new NotImplementedException();
}
private void btnStart_Click(object sender, EventArgs e)
{
_BackgroundWorker.RunWorkerAsync(e);
}
private void btnCancel_Click(object sender, EventArgs e)
{
_BackgroundWorker.CancelAsync();
}