我有以下代码:
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打电话。
有两个问题,首先,这会因为using语句或任何其他原因而阻塞吗?第二,它会破坏任何东西吗?比如泄漏或连接问题?我只想告诉sql server运行一个存储过程,但我不想等待它,我甚至不关心它是否工作。这有可能吗?感谢您的阅读。
发布于 2009-10-09 16:52:46
这不会起作用,因为您正在关闭连接,而查询仍在运行。最好的方法是使用线程池,如下所示:
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。
发布于 2009-10-09 16:53:42
应始终调用EndExecuteNonQuery()方法以防止泄漏。它现在可能可以工作,但谁知道在未来的.NET版本中会发生什么呢。一般规则是始终遵循BeginExecute...使用EndExecute..。
https://stackoverflow.com/questions/1544905
复制相似问题