简体   繁体   English

C#-如果if陈述为true,请尝试两次

[英]C# - Try something twice if if-statement is true

I have a code parsing a website and adding some values to a list. 我有一个解析网站并向列表中添加一些值的代码。 Sometimes I need to parse the website two times and add the second parsevalues to the same list. 有时我需要解析网站两次,然后将第二个parsevalues添加到同一列表中。

This is some of the code: 这是一些代码:

public async Task<IEnumerable<Info>>....
{
var values = new List<Info>();
var request = something;
var request_rewritten = rewritten request to run the second time;
......
if request contains something do all the under two times. Both for the request and the rewritten request and add it to result. 
......
var response = await RequestBytes(request);
var results = Encoding.GetEncoding("iso-8859-1").GetString(response.Content);
_fDom = results;

   try
   {
   do something and a lot of code
   ......
   values.Add(result);
   return result
   }
}

If request contains something I need try try a second time. 如果请求中包含我需要的东西,请尝试再次尝试。 Both for the original request and the rewritten request and add both to the result. 原始请求和重写请求都将两者都添加到结果中。 Can this be done? 能做到吗?

You can follow this pattern. 您可以遵循这种模式。 Add an additional parameter to your method indicating retries remaining. 向您的方法中添加一个附加参数,指示剩余重试次数。

void DoSomething(arg1, arg2, int retriesRemaining = 0)
{
    try
    {
        DoWork();
    }
    catch
    {
        if (retriesRemaining) DoSomething(arg1, arg2, --retriesRemaining);
    }
}

I suppose if you want to avoid writing a method (which is the best answer to your question) you can use a flag: 我想如果您想避免编写方法(这是对问题的最佳答案),则可以使用标志:

bool bRunAgain = true;

while (bRunAgain)
{
   // Your logic, check result and see if you need to run it again

   if (your condition to run again == false)
   {
      bRunAgain = false;
   }
}

Here is a common solution. 这是一个常见的解决方案。 Pass an action to this method and specify retries count 将动作传递给此方法并指定重试次数

public bool ExecuteWithRetry(Action doWork, int maxTries=1) {
   for(var tryCount=1; tryCount<=maxTries; tryCount++){
      try{
         doWork();
      } catch(Exception ex){
         if(tryCount==MaxTriex){
            Console.WriteLine("Oops, no luck with DoWork()");
            return false;
         }
      }
      return true;
   }
}

so in your method 所以用你的方法

void Something(){
  ....
  if(ExecuteWithRetry(()=>NotTrustyMethod(), 2)) {
     //success
  } else {
     //fail
  }


}

void NotTrustyMethod(){ ...}

This solution you can use for any case where you need retry option for methods with any type of arguments (or without them) 此解决方案可用于需要重试选项的情况,该重试选项适用于带有任何类型参数(或不带参数)的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM