如何实现重试的情况下例外,在C#中的n次? [英] How to implement re-try n times in case of exception in C#?

查看:147
本文介绍了如何实现重试的情况下例外,在C#中的n次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个WPF 4.0应用程序中,我们从远程Web服务获取数据。该Web服务公开各地的120多家方法给客户。如果从我的WPF应用程序的Web服务调用失败,我需要重试了N次也就是通过App.config中配置。如何实现这一点?是否有解决这个问题的任何设计模式?

解决方案

 静态牛逼TryNTimes< T>(Func键< T> FUNC,诠释次)
{
  而(次大于0)
  {
     尝试
     {
        返回FUNC();
     }
     赶上(例外五)
     {
       如果(--times&所述; = 0)
          扔;
     }

  }
}
 

I am developing a WPF 4.0 application in which we get the data from a remote web service. The web service exposes around 120+ methods to its clients. If a web service call from my WPF application fails, I need to retry it n times which is configurable via App.Config. How to implement this? Are there any design patterns that address this problem?

解决方案

static T TryNTimes<T>(Func<T> func, int times)
{
  while (times>0)
  {
     try
     {
        return func();
     }
     catch(Exception e)
     {
       if (--times <= 0)
          throw;
     }

  }
}

这篇关于如何实现重试的情况下例外,在C#中的n次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆