我有一个应用程序,有几个方法需要很长时间才能完成。我正在使用backgroundworker来运行这些方法并保持我的UI响应。我的方法看起来像
public void DoSomething()
{
while( HaveMoreWork )
{
// do work
}
}
现在我希望用户界面能够随时取消这个,所以我改变了我的方法来接受像这样的背景工作
public void DoSomething(Backgroundworker worker)
{
while( HaveMoreWork && !worker.CancelationPending )
{
// do work
}
}
我的问题是,有没有更好的方法来做到这一点。似乎将Backgroundwoker作为参数传递给所有这些方法有点混乱。这是什么最佳做法?
答案 0 :(得分:1)
我正在使用全局变量
private BackgroundWorker _bwSearch = new BackgroundWorker();
private void InitializeBackgroundWorker()
{
_bwSearch = new BackgroundWorker();
_bwSearch.WorkerSupportsCancellation = true;
_bwSearch.DoWork += bwSearch_DoWork;
_bwSearch.RunWorkerCompleted += bwSearch_RunWorkerCompleted;
}
单击停止按钮时
private void btnCancel_Click(object sender, EventArgs e)
{
_bwSearch.Abort();
}
<强>更新强> 此外,我正在使用从BackgroundWorker继承的这个简单的助手类
public class AbortableBackgroundWorker : BackgroundWorker
{
private Thread _workerThread;
protected override void OnDoWork(DoWorkEventArgs e)
{
_workerThread = Thread.CurrentThread;
try
{
base.OnDoWork(e);
}
catch (ThreadAbortException)
{
e.Cancel = true;
Thread.ResetAbort();
}
}
public void Abort()
{
if (_workerThread != null)
{
_workerThread.Abort();
_workerThread = null;
}
}
}
答案 1 :(得分:0)
public class DoSomethingService
{
private volatile bool _stopped = false;
public void Start(object socketQueueObject)
{
while (!_stopped)
{
...
}
}
public void Stop()
{
_stopped = true;
}
}
...
var doSomethingService = DoSomethingService();
doSomethingService.Start();
...
doSomethingService.Stop();