如果内部逻辑失败,您将如何实现无限制的重试机制
这样的事情,但在这里你只有一个改变
static void Main(string[] args)
{
ILog Log = LogManager.GetLogger(typeof(Program));
try
{
StartWorking(Log);
}
catch (Exception ex)
{
Log.Error("Main exited with error: {0}. Restarting app", ex);
Thread.Sleep(5000);
StartWorking(Log);
}
}
private static void StartWorking(ILog Log)
{
Foo t = new Foo();
t.ReadConfiguration();
t.Login();
t.StartWorking();
}
答案 0 :(得分:3)
您可以使用while
循环:
while (true)
{
try
{
StartWorking(Log);
// No exception was thrown, exit the loop
break;
}
catch (Exception ex)
{
Log.Error("Main exited with error: {0}. Restarting app", ex);
Thread.Sleep(5000);
}
}
但请注意,这是非常糟糕的做法。你绝对不想这样做。相反,你应该有一个重试逻辑,经过多次重试后才放弃。例如:
const int maxRetries = 5;
for (var i = 0; i < maxRetries; i++)
{
try
{
StartWorking(Log);
// No exception was thrown, exit the loop
break;
}
catch (Exception ex)
{
Log.Error("Main exited with error: {0}. Restarting app", ex);
Thread.Sleep(5000);
}
if (i == maxRetries - 1)
{
throw new Exception("Sorry, we have reached the maximum number of retries for this operation, just giving up");
}
}