2013-08-31 52 views
0

我有一個樂觀併發方法,我需要從中返回一個值。我收到一個錯誤,指出返回變量不在範圍內。樂觀併發返回值

private static string GenerateCustomerId(string contextPath) 
    { 
     var retryMaxCount = 3;    // maximum number of attempts 
     var cycles = 0;     // current attempt 
     Exception exception = null;  // inner exception storage 
     while (cycles++ < retryMaxCount) // cycle control 
     { 
      try 
      { 
       Content sequenceContent = Content.Load(contextPath); 

       int currentSequence; 
       int.TryParse(sequenceContent["LastSequenceNo"].ToString(), out currentSequence); 
       currentSequence++; 

       string currentDate = DateTime.Now.ToString("ddMMyyyy"); 

       string customerID = string.Format("{0}{1}", currentDate, currentSequence); 

       //Save back to content with new update 
       sequenceContent["LastSequenceNo"] = currentSequence.ToString(); 
       sequenceContent["LastCustomerID"] = customerID; 
       sequenceContent.Save(); 


      } 
      catch (NodeIsOutOfDateException e) 
      { 
       exception = e; // storing the exception temporarily 
      } 

      return customerID; //"**Customer ID does not exist in current context**" 
     } 

     // rethrow if needed 
     if (exception != null) 
      throw new ApplicationException("Node is out of date after 3 attempts.", exception); 

    } 

如何返回CustomerID的值?

回答

1

只需將return語句移入try塊 - 然後在該方法的最後添加一個額外的throw語句;如果您遇到方法而沒有的例外,則表明發生了一些非常奇怪的事情。或者你可以只作出最後throw無條件的,當然:

private static string GenerateCustomerId(string contextPath) 
{ 
    var retryMaxCount = 3;    // maximum number of attempts 
    Exception exception = null;  // inner exception storage 
    for (int cycles = 0; cycles < retryMaxCount; cycles++) 
    { 
     try 
     { 
      ... 
      // If we get to the end of the try block, we're fine 
      return customerID; 
     } 
     catch (NodeIsOutOfDateException e) 
     { 
      exception = e; // storing the exception temporarily 
     } 
    } 

    throw new ApplicationException(
     "Node is out of date after " + retryMaxCount + " attempts.", exception); 
} 

順便說一句,我個人避免ApplicationException的 - 我想要麼只是重新拋出原來的異常,或創建一個專用RetryCountExceeded異常或相似的東西。在微軟方面,IMO基本上是一個錯誤。

(另請注意,我已經轉換你的while環路成for循環爲簡單起見,我一定會找到for循環更容易閱讀和理解,而且我懷疑其他大多數開發者有同樣的感覺。我想考慮讓retryMaxCount在你的班級中保持不變,而不是局部變量。)