前言
最近在實作ETL功能的相關系統需要做大量資料的寫入,所以必須確保資料能夠正確寫入以及清除,系統中需要有失敗後重新操作的需求,在重複操作的過程也必須限定操作次數以免系統卡死。
所以參考一些文獻整理後採取以下的方法來實作。
實作方法
在 C# 中,如果 try/catch 中的 try 塊內的程式碼執行失敗,可以使用循環或遞迴的方式來實現重做操作。
具體來說,可以將 try/catch 塊放在循環或遞迴的內部,當 try 塊內的程式碼執行失敗時,就會執行 catch 塊中的程式碼,並重新執行循環或遞迴直到成功為止。下面是一個簡單的範例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| int maxRetries = 3;
int retries = 0;
bool success = false;
do { try { await SomeOperation(); success = true; } catch (Exception ex) { Console.WriteLine($"Error occurred: {ex.Message}");
if (retries < maxRetries) { retries++; Thread.Sleep(1000); } else { break; } } } while (!success && retries < maxRetries);
if (success) { Console.WriteLine("Operation completed successfully!"); } else { Console.WriteLine("Operation failed after max retries!"); }
|