BeginExecuteNonQuery 没有 EndExecuteNonQuery

BeginExecuteNonQuery without EndExecuteNonQuery(BeginExecuteNonQuery 没有 EndExecuteNonQuery)

本文介绍了BeginExecuteNonQuery 没有 EndExecuteNonQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

using (SqlConnection sqlConnection = new SqlConnection("blahblah;Asynchronous Processing=true;")
{
    using (SqlCommand command = new SqlCommand("someProcedureName", sqlConnection))
    {
        sqlConnection.Open();

        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.AddWithValue("@param1", param1);

        command.BeginExecuteNonQuery();
    }
}

我从不调用 EndExecuteNonQuery.

I never call EndExecuteNonQuery.

两个问题,首先这个阻塞是因为using语句还是其他原因?其次,它会破坏任何东西吗?像泄漏或连接问题?我只是想告诉 sql server 运行一个存储过程,但我不想等待它,我什至不在乎它是否有效.那可能吗?感谢阅读.

Two questions, first will this block because of the using statements or any other reason? Second, will it break anything? Like leaks or connection problems? I just want to tell sql server to run a stored procedure, but I don't want to wait for it and I don't even care if it works. Is that possible? Thanks for reading.

推荐答案

这不起作用,因为您在查询仍在运行时关闭了连接.最好的方法是使用线程池,如下所示:

This won't work because you're closing the connection while the query is still running. The best way to do this would be to use the threadpool, like this:

ThreadPool.QueueUserWorkItem(delegate {
    using (SqlConnection sqlConnection = new SqlConnection("blahblah;Asynchronous Processing=true;") {
        using (SqlCommand command = new SqlCommand("someProcedureName", sqlConnection)) {
            sqlConnection.Open();

            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.AddWithValue("@param1", param1);

            command.ExecuteNonQuery();
        }
    }
});

一般来说,当你调用 Begin_Whatever_ 时,你通常必须调用 End_Whatever_ 否则你会泄漏内存.此规则的最大例外是 Control.BeginInvoke.

In general, when you call Begin_Whatever_, you usually must call End_Whatever_ or you'll leak memory. The big exception to this rule is Control.BeginInvoke.

这篇关于BeginExecuteNonQuery 没有 EndExecuteNonQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:BeginExecuteNonQuery 没有 EndExecuteNonQuery

基础教程推荐