C# 重新启动正在运行的函数
我有一个对每个对象调用测试的函数。如果当前测试失败,我希望能够重新测试C# 重新启动正在运行的函数,c#,c#-4.0,C#,C# 4.0,我有一个对每个对象调用测试的函数。如果当前测试失败,我希望能够重新测试 foreach (TestObject test in Tests) { test.RunTest() } //This is in the TestObject class RunTest() { if (failure) {
foreach (TestObject test in Tests)
{
test.RunTest()
}
//This is in the TestObject class
RunTest()
{
if (failure)
{
//Want to be able to run RunTest() again without interrupting the foreach loop.
}
}
有几种方法可以做到这一点,具体取决于你为什么要这样做。你可以: 1) 让
RunTest()
返回boolean
判断成功或失败,然后:
foreach (TestObject test in Tests)
{
while(!test.runTest(){}
}
2) 在RunTest()的内部使用,
:
有几种方法可以做到这一点,具体取决于你为什么要这样做。你可以:
1) 让RunTest()
返回boolean
判断成功或失败,然后:
foreach (TestObject test in Tests)
{
while(!test.runTest(){}
}
2) 在RunTest()的内部使用,
:
对于上面的两个答案,如果失败是合法的(即不是暂时性的失败,我只能猜测你所遇到的是什么),那么解决方案将导致RunTest()永远运行。你可以考虑做一个上面的循环,但是在达到这个阈值之后,保持一个有多少失败和计数的计数。比如:
int FailureThreshold = 3;
foreach (TestObject test in Tests)
{
int failCount = 0;
while (failCount < FailureThreshold)
{
if (test.RunTest())
{
break;
}
else
{
failCount++;
}
}
}
int FailureThreshold=3;
foreach(测试中的测试对象测试)
{
int故障计数=0;
while(故障计数<故障保持)
{
if(test.RunTest())
{
打破
}
其他的
{
故障计数++;
}
}
}
你也应该考虑保持统计需要多少次循环才能通过。这可能是测试稳定性的一个很好的指标。
对于上面的两个答案,如果故障是合法的(即不是暂时性故障,我只能猜测您遇到的是什么),那么解决方案将导致RunTest()永远运行。你可以考虑做一个上面的循环,但是在达到这个阈值之后,保持一个有多少失败和计数的计数。比如:
int FailureThreshold = 3;
foreach (TestObject test in Tests)
{
int failCount = 0;
while (failCount < FailureThreshold)
{
if (test.RunTest())
{
break;
}
else
{
failCount++;
}
}
}
int FailureThreshold=3;
foreach(测试中的测试对象测试)
{
int故障计数=0;
while(故障计数<故障保持)
{
if(test.RunTest())
{
打破
}
其他的
{
故障计数++;
}
}
}
你也应该考虑保持统计需要多少次循环才能通过。这可能是测试稳定性的一个很好的指标。
你们喜欢太多的代码
for (var tryCount = 0; tryCount < 3; tryCount++)
if (test.RunTest())
break;
for(var tryCount=0;tryCount<3;tryCount++)
if(test.RunTest())
打破
。。。哦,我想到了一个更简短的版本。。。但它不是那么干净
for(var-tryCount=0;!test.RunTest()&&tryCount<3;tryCount++);
如果你想重复使用,那么像这样的东西
static bool RunTest(Func<bool> testCase, int maxRetry)
{
for (var tryCount = 0; tryCount < maxRetry; tryCount++)
if (testCase())
return true;
return false;
}
// usage
var testResult = RunTest(test.RunTest, 3);
// or even...
var testResult = RunTest(
{
try {
return test.RunTest();
} catch (Exception ex) {
Debug.WriteLine(ex);
return false;
}
}, 3);
静态bool运行测试(Func testCase,int-maxRetry)
{
for(var tryCount=0;tryCount
你们喜欢太多的代码
for (var tryCount = 0; tryCount < 3; tryCount++)
if (test.RunTest())
break;
for(var tryCount=0;tryCount<3;tryCount++)
if(test.RunTest())
打破
。。。哦,我想到了一个更简短的版本。。。但它不是那么干净
for(var-tryCount=0;!test.RunTest()&&tryCount<3;tryCount++);
如果你想重复使用,那么像这样的东西
static bool RunTest(Func<bool> testCase, int maxRetry)
{
for (var tryCount = 0; tryCount < maxRetry; tryCount++)
if (testCase())
return true;
return false;
}
// usage
var testResult = RunTest(test.RunTest, 3);
// or even...
var testResult = RunTest(
{
try {
return test.RunTest();
} catch (Exception ex) {
Debug.WriteLine(ex);
return false;
}
}, 3);
静态bool运行测试(Func testCase,int-maxRetry)
{
for(var tryCount=0;tryCount