Cleanest way to write retry logic?

前端 未结 29 2585
旧巷少年郎
旧巷少年郎 2020-11-22 03:01

Occasionally I have a need to retry an operation several times before giving up. My code is like:

int retries = 3;
while(true) {
  try {
    DoSomething();
         


        
29条回答
  •  后悔当初
    2020-11-22 03:22

    I'm a fan of recursion and extension methods, so here are my two cents:

    public static void InvokeWithRetries(this Action @this, ushort numberOfRetries)
    {
        try
        {
            @this();
        }
        catch
        {
            if (numberOfRetries == 0)
                throw;
    
            InvokeWithRetries(@this, --numberOfRetries);
        }
    }
    

提交回复
热议问题