2016-12-07 59 views
0

我有一個代碼解析網站並向列表中添加一些值。有時我需要解析網站兩次,並將第二個parsevalues添加到同一個列表中。C# - 如果if語句爲真,請嘗試兩次

這是一些代碼:

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 
    } 
} 

如果請求中包含的東西,我需要試試第二次。原始請求和重寫請求都添加到結果中。這可以做到嗎?

+1

把它放到方法 –

+2

將代碼放入另一個方法,然後調用兩次? – ChrisF

+0

一種常見的計算機編程策略是將問題分成與原始類型相同的子問題,解決這些子問題併合並結果。這通常被稱爲分而治之(divide-and-conquer)方法;當與存儲解決子問題結果的查找表結合使用時(爲了避免重複求解並導致額外的計算時間),它可以被稱爲動態編程或記憶。 –

回答

0

我想,如果你想避免編寫的方法(這是最好的回答你的問題),你可以使用一個標誌:

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; 
    } 
} 
+1

問題海報狀態不想寫一個方法嗎? –

+0

OP的問題的兩個意見都表明創建一個方法,只是提供了另一個解決方案,並且不想在評論中編寫代碼塊 – BackDoorNoBaby

3

您可以遵循這個模式。向您的方法添加一個額外的參數,指示剩餘的重試次數

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

這是一個常見的解決方案。傳遞一個動作這種方法,並指定重試次數

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; 
    } 
} 

所以在你的方法

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


} 

void NotTrustyMethod(){ ...} 

該解決方案可用於在您需要重試選項用於任何類型的參數方法的任何情況下(或沒有他們)