作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
如果我想定期检查是否有取消请求,我会在我的 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)
将您的任务添加到委托(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/
我是一名优秀的程序员,十分优秀!