开发者

Can I dispose of an SqlConnection through a SqlCommand.Disposed event?

Can I attach an event to an SqlCommand.Disposed event that will dispose of the SqlCommand's connection? Here is the code I am testing:

    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();
    }

I w开发者_如何学Pythonant to be able to call the static method GetCommand in a using block and when it is done, dispose of the connection like this:

        using (SqlCommand cmd = GetCommand(query, paramCollection, false))
        {
            //code to execute
        }


Your method should work, but it is really counter-intuitive and I would recommend to rethink the design. Dependant object (command) controlling lifetime of the object it depends on (connection)? What if you want to run more commands on the same connection? What about transactions?


Your code should work fine.
You can test it by setting a breakpoint in the Disposed handler.

You can also shorten it using anonymous methods:

cmd.Disposed += delegate { conn.Dispose(); };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜