gpt4 book ai didi

c# - 如何重用重新打开连接的代码?

转载 作者:太空宇宙 更新时间:2023-11-03 19:25:17 27 4
gpt4 key购买 nike

我们的生产服务器会终止非事件连接,因此我们的 API 需要在需要时恢复它们。下面的代码可以工作,但是重复性很强:

   private const int MaxRetryCount = 3;

public static SqlDataReader RestoreConnectionAndExecuteReader(SqlCommand command)
{
int retryCount = 0;

while (retryCount++ < MaxRetryCount)
{
try
{
if (command.Connection.State == ConnectionState.Closed)
command.Connection.Open();
return command.ExecuteReader();
}
catch(Exception e)
{
if(!e.Message.ToLower().Contains("transport-level error has occurred"))
{
throw;
}
}
}
throw new Exception("Failed to restore connection for command:"+command.CommandText);
}

public static void RestoreConnectionAndExecuteNonQuery(SqlCommand command)
{
var retryCount = 0;
while(retryCount++ < MaxRetryCount)
{
try
{
if (command.Connection.State == ConnectionState.Closed)
command.Connection.Open();
command.ExecuteNonQuery();
return;
}
catch(Exception e)
{
if (!e.Message.ToLower().Contains("transport-level error has occurred"))
{
throw;
}
}
}
throw new Exception("Failed to restore connection for command:" + command.CommandText);
}

我如何重构我的代码并消除重复?我需要保留这些方法的签名,因为它们在整个系统中使用。

最佳答案

private const int MaxRetryCount = 3;

public static T RestoreConnectionAndExecute<T>(SqlCommand command, Func<SqlCommand, T> func)
{
int retryCount = 0;

while (retryCount++ < MaxRetryCount)
{
try
{
if (command.Connection.State == ConnectionState.Closed)
command.Connection.Open();
return func(command);
}
catch(Exception e)
{
if(!e.Message.ToLower().Contains("transport-level error has occurred"))
{
throw;
}
}
}
throw new Exception("Failed to restore connection for command:"+command.CommandText);

}

public static SqlDataReader RestoreConnectionAndExecuteReader(SqlCommand command)
{
return RestoreConnectionAndExecute(command, c => c.ExecuteReader());
}

public static int RestoreConnectionAndExecuteNonQuery(SqlCommand command)
{
return RestoreConnectionAndExecute(command, c => c.ExecuteNonQuery());
}

关于c# - 如何重用重新打开连接的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9120614/

27 4 0
文章推荐: python - Cookie Cumbler 在 Zope 中如何工作?
文章推荐: javascript - 观察vue中的div宽度变化
文章推荐: javascript - 突出显示 HTML 文档中的术语表术语
文章推荐: javascript - 将
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com