Cleanest way to write retry logic?

前端 未结 29 3367
旧巷少年郎
旧巷少年郎 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:40

    Keep it simple with C# 6.0

    public async Task Retry(Func action, TimeSpan retryInterval, int retryCount)
    {
        try
        {
            return action();
        }
        catch when (retryCount != 0)
        {
            await Task.Delay(retryInterval);
            return await Retry(action, retryInterval, --retryCount);
        }
    }
    

提交回复
热议问题