乐观并发返回值

本文关键字:返回值 并发 乐观 | 更新日期: 2023-09-27 18:29:40

我有一个乐观并发方法,需要从中返回一个值。我收到一个错误,指示返回变量不在作用域中。

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

乐观并发返回值

只需将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基本上是微软的一个错误

(还要注意,为了简单起见,我已经将while循环转换为for循环。我肯定会发现for循环更容易阅读和理解,我怀疑大多数其他开发人员也会有同样的感受。我也会考虑将retryMaxCount作为类中的常量,而不是局部变量。)