有没有办法缩短我的BackgroundWorker.CancellationPending
检查点?
例如,是否可以像下面的示例代码一样封装return
?:
//REAL CODE (CURRENTLY USE THIS)
if (this.TW.CancellationPending)
return;
//PSEUDO REPLACEMENT CODE
this.CkPt(CurrentMethod); //PSEUDO USAGE
//^^^ PARAMETER IS A REFERENCE TO THE CURRENT METHOD, SIMILAR TO `this` FOR AN OBJECT
//OR MAYBE AN EXTENSION METHOD WOULD LOOK CLEANER
CurrentMethod.CkPt(); //PSEUDO USAGE
private void CkPt(Method m) //PSEUDO METHOD
{
/*
POSSIBLY PERFORM OTHER CHECKPOINT TASKS HERE
*/
if (this.TW.CancellationPending)
m.return/*FROM METHOD THAT CALLED ME*/;
}
我正在尝试使这样的多检查点情况更具可读性:
//PSUEDO METHOD
//DO NOT TAKE THIS AS REPEATING CODE
//IT IS ONLY MEANT TO SHOW MULTIPLE USES OF THE SAME CHECKPOINT
//MY REAL TASK METHOD(S) CONTAIN MANY MANY MANY AREAS THAT DON'T REPEAT AND REQUIRE CHECKPOINTS
public void FakeBWTask()
{
if (this.TW.CancellationPending)
return;
foreach (var F1 in Fake1)
{
if (this.TW.CancellationPending)
return;
foreach (var F2 in Fake2)
{
if (this.TW.CancellationPending)
return;
foreach (var F3 in Fake3)
{
if (this.TW.CancellationPending)
return;
}
}
}
}
谢谢你的帮助!!
最佳答案
无法调用methodA来调用methodB,而让methodB返回methodA(因为我们没有尾部递归)
考虑使用这样的迭代器。在某些情况下,您可以将try / catch放在检查点之间,这将起作用。
public void FakeBWTask()
{
if (this.TW.CancellationPending)
return;
foreach (object ignore in FakeBWTaskSteps())
{
// Other checkpoint logic here....
if (this.TW.CancellationPending)
return;
}
}
private IEnumerable<object> FakeBWTaskSteps()
{
Part1();
yield return null; // Execute checkpoint logic.
Part2();
yield return null; // Execute checkpoint logic.
Part3();
yield return null; // Execute checkpoint logic.
Part4();
yield return null; // Execute checkpoint logic.
// Do some other stuff.
yield return null; // Execute checkpoint logic.
// final stuff. No looping here.
}
关于c# - C#BackgroundWorker取消检查点缩短,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6934307/