gpt4 book ai didi

C# BackgroundWorker 取消检查点缩短

转载 作者:行者123 更新时间:2023-12-03 21:38:05 31 4
gpt4 key购买 nike

有没有办法缩短我的 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;
}
}
}
}

感谢您的帮助!!

最佳答案

方法A无法调用方法B并让方法B返回方法A(因为我们没有尾递归)

考虑使用这样的迭代器。它适用于某些情况,您可以在检查点之间放置 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# BackgroundWorker 取消检查点缩短,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6934307/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com