【问题标题】:Performing an SQL query while waiting on an asyncronous operation generates an exception在等待异步操作时执行 SQL 查询会产生异常
【发布时间】:2010-10-21 23:29:46
【问题描述】:

我正在编写的代码将数据从一个表复制到另一个表。查询可能会运行很长时间,因此我正在执行异步查询,并在等待时对目标表进行计数以提供状态更新。

进行计数的查询收到以下异常消息...

命令执行无法继续,因为一个挂起的异步操作已经在进行中。

很明显,我的所作所为是不允许的。那么异步SQL操作的规则是什么?还有其他方法可以获取挂起操作的状态吗?

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder( _connectionString );
builder.AsynchronousProcessing = true;

using( SqlConnection connection = new SqlConnection( builder.ConnectionString ) )
{
    connection.Open();

    SqlCommand command = new SqlCommand();
    command.Connection = connection;
    command.CommandType = System.Data.CommandType.Text;
    command.CommandText = "INSERT INTO DestTable SELECT * FROM SourceTable";

    IAsyncResult result = command.BeginExecuteNonQuery();

    using( SqlConnection statusConnection = new SqlConnection( _connectionString ) )
    {
        while( !result.IsCompleted )
        {
            SqlCommand statusCommand = new SqlCommand();
            statusCommand.Connection = statusConnection;
            statusCommand.CommandType = System.Data.CommandType.Text;
            statusCommand.CommandText = "SELECT COUNT(*) FROM DestTable";

            int currentRowCount = (int)command.ExecuteScalar();

            Thread.Sleep( 500 );
        }

        command.EndExecuteNonQuery( result );
    }
}

【问题讨论】:

  • 请用您正在使用的数据库产品(Oracle、SQL Server 等)标记这个问题。

标签: sql exception asynchronous


【解决方案1】:

您似乎正在尝试使用相同的命令。

我认为你想替换

int currentRowCount = (int)command.ExecuteScalar();

int currentRowCount = (int)statusCommand.ExecuteScalar();

您正在尝试使用相同的语句,由于第一次执行应该被阻止。

【讨论】:

    猜你喜欢
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 2015-11-09
    • 1970-01-01
    相关资源
    最近更新 更多