首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >对于捕获SQLException和重试,什么是好的C#编码风格

对于捕获SQLException和重试,什么是好的C#编码风格
EN

Stack Overflow用户
提问于 2011-01-28 04:46:43
回答 5查看 17.2K关注 0票数 19

我有一个方法,它调用SQLServer函数对表执行自由文本搜索。该函数偶尔会在第一次调用时导致SQLException:“全文查询字符串的断字超时”。因此,通常我希望重试该请求,因为它将在后续请求中成功。什么是构建重试逻辑的好风格。目前我有以下几点:

代码语言:javascript
复制
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;
EN

回答 5

Stack Overflow用户

发布于 2011-07-04 17:04:28

我的sql可重试枚举如下所示:

代码语言:javascript
复制
SqlConnectionBroken = -1,
SqlTimeout = -2,
SqlOutOfMemory = 701,
SqlOutOfLocks = 1204,
SqlDeadlockVictim = 1205,
SqlLockRequestTimeout = 1222,
SqlTimeoutWaitingForMemoryResource = 8645,
SqlLowMemoryCondition = 8651,
SqlWordbreakerTimeout = 30053
票数 8
EN

Stack Overflow用户

发布于 2011-01-28 04:52:32

这不是一种好的风格,但有时你必须这样做,因为你根本不能改变现有的代码并必须处理它。

我在这个场景中使用了下面的泛型方法。请注意PreserveStackTrace()方法,它有时在重新抛出的场景中非常有用。

代码语言:javascript
复制
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);
}

你可以这样称呼它:

代码语言:javascript
复制
RetryBeforeThrow<SqlException>(() => MethodWhichFails(), 3, 100);
票数 7
EN

Stack Overflow用户

发布于 2011-01-28 04:51:34

我认为使用指定重试计数的方面来注释一个方法会导致更多结构化的代码,尽管它需要一些基础设施编码。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4821668

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档