2017-02-26 63 views
-1

重試機制,你怎麼會在情況下,內部邏輯實現無限的重試機制無法落實爲主線

這樣的事情,但在這裏,你只有一個變化

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(); 
    } 

回答

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"); 
    } 
} 
+1

在許多現實世界的場景也非常有用使用指數退避(增加睡眠時間呈指數達到一定的量),而不是每次都睡固定的5秒。 – Evk