如果拋出某種例外型別,我想重新運行一個 C# 任務。
這是我目前擁有的:
bool retry = true;
int numOfRetries = 3;
int tries;
while (retry = true && tries <= numOfRetries)
{
try
{
//Task
retry = false;
}
catch (Exception e)
{
if (e.Message.Contains("Unique exception Id like to retry on")
{
tries ;
}
else
{
retry = false;
log(e);
}
}
}
uj5u.com熱心網友回復:
我建議使用fornot while:
for (int retry = 1; retry <= numOfRetries; retry) {
try {
DoSomething();
break; // stop looping on success
}
catch (Exception e) {
//TODO: put here condition on e where you should retry
if (!condition) { // <- no retry
log(e);
// you may want to rethrow the exception: throw;
break; // no more retries on unwanted exception
}
}
}
如果您想捕獲某些例外型別:
for (int retry = 1; retry <= numOfRetries; retry) {
try {
DoSomething();
break; // stop looping on success
}
catch MyException1:
catch MyException2:
catch MyExceptionN:
; // catch and do nothing but retry
catch (Exception e) {
// no retry
log(e);
// you may want to rethrow the exception: throw;
break; // no more retries on unwanted exception
}
}
uj5u.com熱心網友回復:
看看 Polly 庫:https ://github.com/App-vNext/Polly 有很好的重試策略,很容易實作。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/511445.html
