【发布时间】:2014-06-23 07:24:07
【问题描述】:
我正在制作一个应该 24/7 全天候运行的系统,并带有计时器来控制它。有许多对数据库的调用,在某些时候,有两种方法试图打开一个连接,其中一种会失败。我试图制作一个重试方法,所以我的方法会成功。在 Better way to write retry logic without goto 中的 Michael S. Scherotter 和 Steven Sudit 方法的帮助下,我的方法是否如下所示:
int MaxRetries = 3;
Product pro = new Product();
SqlConnection myCon = DBcon.getInstance().conn();
string barcod = barcode;
string query = string.Format("SELECT * FROM Product WHERE Barcode = @barcode");
for (int tries = MaxRetries; tries >= 0; tries--) //<-- 'tries' at the end, are unreachable?.
{
try
{
myCon.Open();
SqlCommand com = new SqlCommand(query, myCon);
com.Parameters.AddWithValue("@barcode", barcode);
SqlDataReader dr = com.ExecuteReader();
if (dr.Read())
{
pro.Barcode = dr.GetString(0);
pro.Name = dr.GetString(1);
}
break;
}
catch (Exception ex)
{
if (tries == 0)
Console.WriteLine("Exception: "+ex);
throw;
}
}
myCon.Close();
return pro;
运行代码时,程序停在“for(.....)”处,出现异常:连接未关闭。连接的当前状态是打开的......这个问题是我尝试使用这种方法的原因!如果有人知道如何解决这个问题,请写信。谢谢
【问题讨论】:
标签: c#