【问题标题】:Retry a service call ONLY ONCE in the event service fails logic help在事件服务失败逻辑帮助中仅重试一次服务调用
【发布时间】:2010-12-21 23:48:13
【问题描述】:

所以我有一个调用 Web 服务的函数,该函数将返回一个 INT 指示成功或可能发生的各种类型的失败。在收到服务的结果后,我会运行一个 switch 语句,并根据服务执行期间遇到的情况进行相应的处理。

private void Example()
{

int Result = ExecuteWebService();

switch(Result)
{
case 0:
//no errors
NoErrorsLogic();
break;
case 1:
// manual retry 
ManualRetryLogic();
break;
case 2:
//  validation error
ValidationErrorLogic();
break;
default:
// Run time error occurred
LogicOptionD();
// At this point I want to to call the service again ONCE just to see if it will succeed
break;
}

}

一般来说,我只是添加对函数的调用,以便它调用服务并重新运行结果,但我不希望它继续运行直到服务成功。在默认选项中,我只想强制它“重试”一次调用服务 - 然后相应地处理结果。

有什么想法吗?

【问题讨论】:

    标签: c# visual-studio-2010


    【解决方案1】:

    你总是可以这样做的:

    private void Example(bool retry = true)
    {
    
    
    ....
    default:
    
    if(retry)
    {
      Example(false);
    }
    break;
    }
    

    只需添加一个参数并在失败时让函数自行调用。你传入参数的 false 值,告诉函数如果它再次失败,不要做任何事情。

    在 C# 4.0 Example(bool retry = true) 中,您可以设置默认值,因此您不必担心现有代码没有设置真实值。在 3.5 或更低版本中,只需创建一个带参数的重载方法和一个不带参数的方法。没有的直接调用有so的:

    Example()
    {
       Example(true);
    }
    

    【讨论】:

      【解决方案2】:

      虽然我同意 Kevin 的做法,但这里还有一个:

      bool success = false;
      bool retry = true;
      while (!success)
      {
          success = true;
          int Result = ExecuteWebService();
      
          switch(Result)
          {
          case 0:
              //no errors
              NoErrorsLogic();
              break;
          case 1:
              // manual retry 
              ManualRetryLogic();
              break;
          case 2:
              //  validation error
              ValidationErrorLogic();
              break;
          default:
              // Run time error occurred
              LogicOptionD();
              success = !retry;
              retry = false;
              break;
          }
      
      }
      

      这将确保如果 Example 中有另一个逻辑,无论如何它都会被调用一次,并且您不需要将服务调用和响应处理代码放在单独的方法中(不过我建议这样做) .

      【讨论】:

        猜你喜欢
        • 2014-11-29
        • 2011-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-18
        • 1970-01-01
        • 2023-03-29
        • 1970-01-01
        相关资源
        最近更新 更多