C#清洁写重试逻辑的方式?

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

有时候予有需要之前放弃重试操作几次。我的code是这样的:

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#中?会是什么code为 TryThreeTimes()的方法?

推荐答案

毛毯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 retryCount = 3) { Do<object>(() => { action(); return null; }, retryInterval, retryCount); } public static T Do<T>( Func<T> action, TimeSpan retryInterval, int retryCount = 3) { var exceptions = new List<Exception>(); for (int retry = 0; retry < retryCount; retry++) { try { if (retry > 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);

或者,你甚至可以使一个异步过载。

更多推荐

C#清洁写重试逻辑的方式?

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

发布评论

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

>www.elefans.com

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