c# – 使用Delegates执行1次重试的任何方法的通用方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 使用Delegates执行1次重试的任何方法的通用方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1803字,纯文字阅读大概需要3分钟。
内容图文
![c# – 使用Delegates执行1次重试的任何方法的通用方法](/upload/InfoBanner/zyjiaocheng/811/6732a6edb5664515a76d232eeb40dc95.jpg)
我正在尝试开发一种机制,使用该机制我可以执行1次重试尝试的任何方法.
如果在第一次运行中遇到异常,将触发重试.
基本的想法是,我将有一个用于重试逻辑的泛型类,我想通过委托传递任何方法.并且该方法将在1次重试时执行.
到目前为止我已经开发了这个.
public class RetryHandler
{
Delegate _methodToRetry;
// default constructor with delegate to function name.
public RetryHandler(Delegate MethodToExecuteWithRetry)
{
_methodToRetry = MethodToExecuteWithRetry;
}
public void ExecuteWithRetry(bool IsRetryEnabled)
{
try
{
_methodToRetry.DynamicInvoke();
}
catch (Exception ex)
{
if (IsRetryEnabled)
{
// re execute method.
ExecuteWithRetry(false);
}
else
{
// throw exception
throw;
}
}
}
}
现在我有一个问题:
我想传递的方法有不同的输入参数(由参数和对象类型的数量)和不同的输出参数.
有什么办法可以实现这个目标吗?基本上我想调用这样的方法:
RetryHandler rh = new RetryHandler(MyMethod1(int a, int b));
int output = (int) rh.ExecuteWithRetry(true);
RetryHandler rh2 = new RetryHandler(MyMethod2(string a));
string output2 = (string) rh2.ExecuteWithRetry(true);
任何帮助将非常感激.谢谢.
解决方法:
>试试这个:
public void ExecuteWithRetry(bool IsRetryEnabled, params object[] args)
{
try
{
_methodToRetry.DynamicInvoke(args);
}
catch (Exception ex)
{
if (IsRetryEnabled)
{
// re execute method.
ExecuteWithRetry(false, args);
并像这样调用:int output =(int)rh.ExecuteWithRetry(true,a,b);
>另一个选项是rwrite RetryHandler作为泛型方法,但是你需要为任何参数计数编写代码:
public static TReturn ExecuteWithRetry<TReturn, TParam>(bool IsRetryEnabled, Func<TParam, TReturn> func, TParam param)
{
// ...
return func(param);
// ...
}
>或编写通用扩展方法,以便您可以调用:
var f = new Func<int, int>((a) => a + 1);
f.ExecuteWithRetry(x);
扩展类:
public static class Ext
{
public static TReturn ExecuteWithRetry<TReturn, TParam>(this Func<TParam, TReturn> func, TParam param)
{
return func(param);
}
}
内容总结
以上是互联网集市为您收集整理的c# – 使用Delegates执行1次重试的任何方法的通用方法全部内容,希望文章能够帮你解决c# – 使用Delegates执行1次重试的任何方法的通用方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。