【发布时间】:2016-03-08 09:55:33
【问题描述】:
如果有特定的SqlException(例如连接丢失),我必须修改用于处理我的 SQL 调用的静态类,以便重试请求。
这是我用来调用存储过程的方法:
public static int CallExecuteNonQuery(string storedProcName, Action<SqlCommand> fillParamsAction, Action afterExecution, BDDSource source)
{
int result;
try
{
using (var connection = InitSqlConnection(source))
using (var command = new SqlCommand(storedProcName, connection))
{
if (connection.State == ConnectionState.Closed)
connection.Open();
command.CommandType = CommandType.StoredProcedure;
if (fillParamsAction != null)
fillParamsAction(command);
result = command.ExecuteNonQuery();
if (afterExecution != null)
afterExecution();
}
}
catch (SqlException sqlExn)
{
Logger.Exception(string.Format("SQL CRITICAL ERROR. Stored Proc Name : {0}", storedProcName), sqlExn);
throw;
}
catch (Exception exception)
{
Logger.Exception(string.Format("SOFTWARE CRITICAL ERROR. Stored Proc Name : {0}", storedProcName), exception);
throw;
}
return result;
}
在this link 之后,我正在尝试按照配置的次数重试请求。
我得到以下代码:
public static int CallExecuteNonQuery(string storedProcName, Action<SqlCommand> fillParamsAction, Action afterExecution, BDDSource source)
{
bool RetryRequest = true;
int result = 0;
for (int i = 0; i < Properties.Settings.Default.Request_MaximumRetry; i++)
{
try
{
if (RetryRequest)
{
using (var connection = InitSqlConnection(source))
using (var command = new SqlCommand(storedProcName, connection))
{
if (connection.State == ConnectionState.Closed)
connection.Open();
command.CommandType = CommandType.StoredProcedure;
if (fillParamsAction != null)
fillParamsAction(command);
result = command.ExecuteNonQuery();
if (afterExecution != null)
afterExecution();
}
RetryRequest = false;
}
}
catch (SqlException sqlExn)
{
if (sqlExn.Errors.Cast<SqlError>().All(x => (x.Class >= 16 && x.Class < 22) || x.Class == 24))
{
RetryRequest = true;
continue;
}
Logger.Exception(string.Format("SQL CRITICAL ERROR. Stored Proc Name : {0}", storedProcName), sqlExn);
RetryRequest = false;
throw;
}
catch (Exception exception)
{
Logger.Exception(string.Format("SOFTWARE CRITICAL ERROR. Stored Proc Name : {0}", storedProcName), exception);
RetryRequest = false;
throw;
}
}
return result;
}
但我的修改并不完美。例如,在异常重试 3 次后,代码不会抛出,而是在退出循环之前进入 continue; 部分。
【问题讨论】:
标签: c# .net sql-server