如果我想定期检查是否有取消请求,请在我的DoWork事件处理程序中不断使用以下代码:
if(w.CancellationPending == true)
{
e.Cancel = true;
return;
}
有没有一种干净的方法来检查C#中
BackgroundWorker
中的取消请求,而不必一遍又一遍地重新键入相同的代码?请引用以下代码:
void worker_DoWork(object sender, DoWorkEventArgs e)
{
...
BackgroundWorker w = sender as BackgroundWorker;
if(w.CancellationPending == true)
{
e.Cancel = true;
return;
}
some_time_consuming_task...
if(w.CancellationPending == true)
{
e.Cancel = true;
return;
}
another_time_consuming_task...
if(w.CancellationPending == true)
{
e.Cancel = true;
return;
}
...
}
最佳答案
使用while循环并委派
将您的任务添加到委托(delegate)列表中,然后循环测试您的条件。
您可以使用Action自定义委托(delegate)来简化此任务(请参阅:http://msdn.microsoft.com/en-us/library/system.action(v=vs.110).aspx)
void worker_DoWork(object sender, DoWorkEventArgs e)
{
List<Action> delegates = new List<Action>();
delegates.add(some_time_consuming_task);
delegates.add(another_time_consuming_task);
BackgroundWorker w = sender as BackgroundWorker;
while(!w.CancellationPending && delegate.Count!=0)
{
delegates[0]();
delegates.remove(0);
}
if(w.CancellationPending)
e.Cancel = true;
}
关于c# - 有没有一种干净的方法来检查BackgroundWorker中的取消请求,而不必一遍又一遍地重新键入相同的代码?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26629852/