编写重试逻辑的最简洁方法?

编程入门 行业动态 更新时间:2024-10-08 08:25:36
本文介绍了编写重试逻辑的最简洁方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有时我需要在放弃之前重试几次操作.我的代码是这样的:

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(); break; // success! } catch { if(--retries == 0) throw; else Thread.Sleep(1000); } }

我想在一个通用的重试函数中重写这个:

I would like to rewrite this in a general retry function like:

TryThreeTimes(DoSomething);

在 C# 中可以吗?TryThreeTimes() 方法的代码是什么?

Is it possible in C#? What would be the code for the TryThreeTimes() method?

推荐答案

简单地重试相同调用的一揽子 catch 语句如果用作一般异常处理机制可能是危险的.话虽如此,这里有一个基于 lambda 的重试包装器,您可以将其与任何方法一起使用.我选择将重试次数和重试超时作为参数考虑在内,以获得更大的灵活性:

Blanket catch statements that simply retry the same call can be dangerous if used as a general exception handling mechanism. Having said that, here's a lambda-based retry wrapper that you can use with any method. I chose to factor the number of retries and the retry timeout out as parameters for a bit more flexibility:

public static class Retry { public static void Do( Action action, TimeSpan retryInterval, int maxAttemptCount = 3) { Do<object>(() => { action(); return null; }, retryInterval, maxAttemptCount); } public static T Do<T>( Func<T> action, TimeSpan retryInterval, int maxAttemptCount = 3) { var exceptions = new List<Exception>(); for (int attempted = 0; attempted < maxAttemptCount; attempted++) { try { if (attempted > 0) { Thread.Sleep(retryInterval); } return action(); } catch (Exception ex) { exceptions.Add(ex); } } throw new AggregateException(exceptions); } }

您现在可以使用此实用程序方法来执行重试逻辑:

You can now use this utility method to perform retry logic:

Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1));

或:

Retry.Do(SomeFunctionThatCanFail, TimeSpan.FromSeconds(1));

或:

int result = Retry.Do(SomeFunctionWhichReturnsInt, TimeSpan.FromSeconds(1), 4);

或者您甚至可以进行 async 重载.

Or you could even make an async overload.

更多推荐

编写重试逻辑的最简洁方法?

本文发布于:2023-11-26 07:43:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633233.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:重试   简洁   逻辑   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!