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 的值?

4

1 回答 1

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异常或类似的东西。ApplicationException基本上是微软的一个错误,IMO。

(另请注意,为简单起见,我已将您的while循环转换为for循环。我肯定会发现for循环更易于阅读和理解,而且我怀疑大多数其他开发人员也会有同样的感觉。我会考虑retryMaxCount在您的课程中制作一个常量而不是局部变量。)

于 2013-08-31T08:08:50.377 回答