我正在csharp(.net 4.0)中构建一个消息传递应用程序,我的类有发送/接收消息的基本方法:
void sendMessage( string msgBody, string properties);
object getNextMessage();
object getMessageById( string msgId);
这些方法中的每一种都取决于底层连接;如果连接是陈旧的,我使用try / catch和一些重试逻辑来进行额外的尝试,如下所示:
public object getNextMessage(){
object nextMessage = null;
int retryAttempts = 0;
int MAX_ATTEMPTS = 3;
while( retryAttempts < MAX_ATTEMPTS){
retryAttempts++;
try{
nextMessage = connection.getMessage("queueName");
}catch(Exception e){
}
}
return nextMessage;
}
由于重试逻辑是通用的,我想避免在每个方法中重复相同的代码。我想创建一个通用的重试函数,并执行以下操作:
public object makeAttempt( CodeBlock codeBlock){
while( retryAttempts < MAX_ATTEMPTS){
retryAttempts++;
try{
return codeBlock.invoke()
}catch(Exception e){
}
}
return null;
}
..我想像这样使用makeAttempt
或类似的东西:
public object getNextMessage(){
makeAttempt() => {
return connection.getMessage("queueName");
}
}
我回顾了this,但它涉及将整个函数作为参数传递,我没有这样做。我还审核了.net Lambda Expressions,但我没有看到连接。
我没有做太多C#所以请原谅n00b问题: - )
答案 0 :(得分:9)
你最后几乎就在那里 - 你只需将lambda表达式括在()
中,因为它是一个方法参数。您还需要使用makeAttempt
的返回值来为getNextMessage
方法提供返回值。所以:
public object getNextMessage(){
return makeAttempt(() => {
return connection.getMessage("queueName");
});
}
或者更简单地说,使用表达式lambda:
public object getNextMessage(){
return makeAttempt(() => connection.getMessage("queueName"));
}
这是假设CodeBlock
是委托类型,当然,例如
public delegate object CodeBlock();
您还需要更改makeAttempt
以致电Invoke
而不是invoke
- C#区分大小写。我强烈建议您遵循.NET命名约定,方法是PascalCased
而不是camelCased
。
编辑:正如评论中所述,你可以使这个通用:
public T CallWithRetries<T>(Func<T> function)
{
for (int attempt = 1; attempt <= MaxAttempts; attempt++)
{
try
{
return function();
}
catch(Exception e)
{
// TODO: Logging
}
}
// TODO: Consider throwing AggregateException here
return default(T);
}