gen*_*ene 4 .net c# idisposable sqlconnection try-catch
我正在与SqlConnection和一起工作SqlCommand。
例如,如果有任何SqlException.
我正在使用using子句并将其嵌入try/catch block其中。这是代码:
public static void LogError(string error, string message)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["connStringWeb"]))
using (SqlCommand cmd = new SqlCommand("INSERT INTO errorLogTable (errorTime, errorType, error) VALUES(@errorTime, @errorText, @errorMsg)"))
{
cmd.CommandTimeout = 300;
cmd.Connection = conn;
cmd.Prepare();
cmd.Parameters.AddWithValue("@errorTime", DateTime.Now);
cmd.Parameters.AddWithValue("@errorText", error);
cmd.Parameters.AddWithValue("@errorMsg", message);
try
{
conn.Open();
int i = cmd.ExecuteNonQuery();
}
catch { }
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果出现异常,我的SqlConnection和是否会SqlCommand被处理,这是处理它的好方法还是我应该简单地使用使用try/catch/finally块的旧时尚方法?
该using语句只是try/finally块的语法快捷方式。所以是的,在using抛出异常的情况下,内部的对象将被处理。换一种方式:
using(var foo = new Foo())
{
}
Run Code Online (Sandbox Code Playgroud)
基本上被编译成:
Foo foo;
try
{
foo = new Foo();
}
finally
{
foo.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1734 次 |
| 最近记录: |