我有一个方法,它调用SQLServer函数对表执行自由文本搜索。该函数偶尔会在第一次调用时导致SQLException:“全文查询字符串的断字超时”。因此,通常我希望重试该请求,因为它将在后续请求中成功。什么是构建重试逻辑的好风格。目前我有以下几点:
var retryCount = 0;
var results = new List<UserSummaryDto>();
using (var ctx = new UsersDataContext(ConfigurationManager.ConnectionStrings[CONNECTION_STRING_KEY].ConnectionString))
{
for (; ; )
{
try
{
results = ctx.SearchPhoneList(value, maxRows)
.Select(user => user.ToDto())
.ToList();
break;
}
catch (SqlException)
{
retryCount++;
if (retryCount > MAX_RETRY) throw;
}
}
}
return results;发布于 2011-07-04 17:04:28
我的sql可重试枚举如下所示:
SqlConnectionBroken = -1,
SqlTimeout = -2,
SqlOutOfMemory = 701,
SqlOutOfLocks = 1204,
SqlDeadlockVictim = 1205,
SqlLockRequestTimeout = 1222,
SqlTimeoutWaitingForMemoryResource = 8645,
SqlLowMemoryCondition = 8651,
SqlWordbreakerTimeout = 30053发布于 2011-01-28 04:52:32
这不是一种好的风格,但有时你必须这样做,因为你根本不能改变现有的代码并必须处理它。
我在这个场景中使用了下面的泛型方法。请注意PreserveStackTrace()方法,它有时在重新抛出的场景中非常有用。
public static void RetryBeforeThrow<T>(Action action, int retries, int timeout) where T : Exception
{
if (action == null)
throw new ArgumentNullException("action", string.Format("Argument '{0}' cannot be null.", "action"));
int tries = 1;
do
{
try
{
action();
return;
}
catch (T ex)
{
if (retries <= 0)
{
PreserveStackTrace(ex);
throw;
}
Thread.Sleep(timeout);
}
}
while (tries++ < retries);
}
/// <summary>
/// Sets a flag on an <see cref="T:System.Exception"/> so that all the stack trace information is preserved
/// when the exception is re-thrown.
/// </summary>
/// <remarks>This is useful because "throw" removes information, such as the original stack frame.</remarks>
/// <see href="http://weblogs.asp.net/fmarguerie/archive/2008/01/02/rethrowing-exceptions-and-preserving-the-full-call-stack-trace.aspx"/>
public static void PreserveStackTrace(Exception ex)
{
MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
preserveStackTrace.Invoke(ex, null);
}你可以这样称呼它:
RetryBeforeThrow<SqlException>(() => MethodWhichFails(), 3, 100);发布于 2011-01-28 04:51:34
我认为使用指定重试计数的方面来注释一个方法会导致更多结构化的代码,尽管它需要一些基础设施编码。
https://stackoverflow.com/questions/4821668
复制相似问题