我正在尝试使用 ReliableSqlConnection 类(来自Transient Fault Handling Application Block NuGet包)。
我的最终结果是我想使用可靠的重试机制填充GridView。
我的代码如下所示:
RetryStrategy retryStrategy = new Incremental("incremental", 5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));
RetryPolicy retryPolicy = new RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(retryStrategy);
IList<RetryStrategy> strategies = new List<RetryStrategy> { retryStrategy };
RetryManager manager = new RetryManager(strategies, "incremental");
RetryManager.SetDefault(manager);
using (ReliableSqlConnection connection =
new ReliableSqlConnection(
ConfigurationManager.ConnectionStrings["AdventureWorksLTConnectionString"].ConnectionString,
retryPolicy))
{
SqlCommand command = new SqlCommand(
"SELECT top 5 [FirstName], [LastName], [CompanyName], [EmailAddress] FROM [SalesLT].[Customer]",
connection.Current);
command.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable table = new DataTable();
adapter.Fill(table);
GridView1.DataSource = table.DefaultView;
GridView1.DataBind();
}
这里的 Fill 方法是否在内部使用 ExecuteReaderWithRetry 方法?它需要吗?或者是否仅使用 ReliableSqlConnection 作为我的连接自动设置为重试?
从文档中可以清楚地了解这一切是如何在幕后工作的。
答案 0 :(得分:2)
也许这会奏效?尚未测试过。
retryPolicy.ExecuteAction(() =>
{
adapter.Fill(table);
});
修改我的代码片段:
retryPolicy.ExecuteAction(() =>
{
using (SqlConnection con = new SqlConnection(GetConStr()))
{
com.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(com);
con.OpenWithRetry();
da.Fill(dt);
}
});
我需要Azure SQL
答案 1 :(得分:0)
也许这会奏效?尚未测试过。
DataTable GetTable(string commandText)
{
DataTable DataTable = null;
DataTable TempDataTable = null;
try
{
TempDataTable = new DataTable();
TempDataTable.Locale = CultureInfo.InvariantCulture;
using (ReliableSqlConnection ReliableSqlConnection = new ReliableSqlConnection(ConnectionString))
{
ReliableSqlConnection.Open();
using (SqlCommand SqlCommand = new SqlCommand(commandText, ReliableSqlConnection.Current))
{
SqlCommand.CommandType = CommandType.Text;
TempDataTable.Load(SqlCommand.ExecuteReaderWithRetry());
}
}
DataTable = TempDataTable;
TempDataTable = null;
}
finally
{
if (TempDataTable != null)
{
TempDataTable.Dispose();
}
}
return DataTable;
}