我可以将事件附加到将处置SqlCommand连接的SqlCommand.Disposed事件吗?这里是我的测试代码:可以通过SqlCommand.Disposed事件处理SqlConnection吗?
public static SqlCommand GetCommand(string query, SqlParameter[] paramCollection, bool isStoredProcedure)
{
return new DBSettings().CreateCommand(query, paramCollection, isStoredProcedure);
}
public SqlCommand CreateCommand(string query, SqlParameter[] paramCollection, bool isStoredProcedure)
{
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
if (paramCollection.Length > 0)
cmd.Parameters.AddRange(paramCollection);
if (isStoredProcedure)
cmd.CommandType = CommandType.StoredProcedure;
cmd.Disposed += new EventHandler(cmd_Disposed);
return cmd;
}
protected void cmd_Disposed(object sender, EventArgs e)
{
SqlCommand cmd = (SqlCommand)sender;
cmd.Connection.Dispose();
}
我希望能够调用静态方法GetCommand在使用块,当它完成,处理这样的连接:
using (SqlCommand cmd = GetCommand(query, paramCollection, false))
{
//code to execute
}
当连接字符串相同时,.NET Framework会自动缓存打开的SqlConnections。所以如果一个连接打开并且另一个SqlCommand执行,它将使用相同的连接。我一直在使用代码,它似乎执行得非常快。但我会接受你的建议。这是我正在改变委托给:cmd.Disposed + =委托{if(conn.State!= ConnectionState.Executing && conn.State!= ConnectionState.Fetching && conn.State!= ConnectionState.Connecting){conn.Dispose (); }}; – deccks 2010-11-08 19:34:42