使用BeginExecuteNonQuery db的asp.net异步调用未触发

时间:2011-04-18 17:06:09

标签: asp.net

我的代码触发了ExecuteNonQueryAsyc。在调试中我看到它命中了command.BeginExecuteNonQuery(new AsyncCallback(AsyncCommandCompletionCallback),command); 但是,sp并没有真正被激活而被调用。我做错了什么?

public static void ExecuteNonQueryAsyc(string procedureName, IList<SqlParameter> parameters)
{
    using (SqlConnection connection = new SqlConnection(Config.GetDbConnection() + ";Async=true;"))
    {
        SqlCommand command = connection.CreateCommand();

        command.CommandText = procedureName;
        command.CommandType = CommandType.StoredProcedure;

        if (parameters != null)
            for (int index = 0; index < parameters.Count; index++)
                command.Parameters.Add(parameters[index]);

            connection.Open();
            command.BeginExecuteNonQuery(new AsyncCallback(AsyncCommandCompletionCallback), command);

    }
}

static void AsyncCommandCompletionCallback(IAsyncResult result)
{
    SqlCommand cmd = null;
    try
    {
        // Get our command object from AsyncState, then call EndExecuteNonQuery.
        cmd = (SqlCommand)result.AsyncState;
        cmd.EndExecuteNonQuery(result);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        cmd.Connection.Close();
        cmd.Dispose();
    }
}

1 个答案:

答案 0 :(得分:2)

刚出现同样的问题,所以尽管答案在评论中:

using (SqlConnection connection = new SqlConnection(Config.GetDbConnection() + ";Async=true;"))

导致连接在命令完成之前关闭(可能在它真正被调用之前,因为它在另一个线程上,可能需要几个滴答来启动并开始)。