C# 返回值的乐观并发
我有一个乐观并发方法,需要从中返回一个值。我收到一个错误,指示返回变量不在范围内C# 返回值的乐观并发,c#,C#,我有一个乐观并发方法,需要从中返回一个值。我收到一个错误,指示返回变量不在范围内 private static string GenerateCustomerId(string contextPath) { var retryMaxCount = 3; // maximum number of attempts var cycles = 0; // current attempt
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);
}
私有静态字符串GenerateCustomerId(字符串上下文路径)
{
var retryMaxCount=3;//最大尝试次数
var cycles=0;//当前尝试
异常异常=null;//内部异常存储
while(cycles++
如何返回CustomerID的值?只需将
return
语句移动到try
块中,然后在方法的最后添加一个额外的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);
}
私有静态字符串GenerateCustomerId(字符串上下文路径)
{
var retryMaxCount=3;//最大尝试次数
异常异常=null;//内部异常存储
对于(int cycles=0;cycles
顺便说一句,我个人会避免ApplicationException
——我要么重新调用原始异常,要么创建一个专用的retrycountexception
异常或类似的异常ApplicationException
基本上是微软方面的一个错误,IMO
(也请注意,为了简单起见,我已经将<<代码> /<代码>循环转换为<代码> < <代码>循环】。我肯定会发现< <代码> > <代码>循环更容易阅读和理解,而且我猜想大多数其他开发人员也会有同样的感受。我会考虑在类中使用<代码> RejyMax计数<代码>一个常数,而不是一个局部变量T。哦。)