【发布时间】:2013-08-05 20:22:17
【问题描述】:
我想知道下面的代码模式:
static SqlConnection getcon()
{
SqlConnection con = new SqlConnection("data source=foobar..");
con.Open();
// is con Disposed automatically or will it leak and live
// forever when exception is thrown?
throw new Exception("exception");
return con;
}
static void Main(string[] args)
{
try
{
using (var scope = new TransactionScope())
using (var con = getcon())
using (var cmd = new SqlCommand("UPDATE SomeTable SET Column1 = 'test'", con))
{
cmd.ExecuteNonQuery();
scope.Complete();
}
}
catch
{
}
}
这是使用SqlConnection 的安全方法吗(从getcon() 方法获取连接)?当抛出异常时,它会在函数退出后被释放还是会永远存在?
我想要这个GetCon() 方法的目的是缩短代码并将连接创建和打开包装在一行中(using (var con = getcon())..)
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
-
好的!但是,即使在“使用”行中发生异常,而不是在大括号 { } 内,连接是否也会被处理?
-
为了避免输入 一行 代码 (
conn.Open()) 来解决所有这些麻烦(并可能导致副作用和错误)似乎是非常错误的和过早的优化 - 不要这样做。这不值得。
标签: c# sqlconnection