繁体   English   中英

ADO.Net SqlCommand.EndExecuteReader上的SQLException

[英]SQLException on ADO.Net SqlCommand.EndExecuteReader

我正在尝试通过ADO.Net SqlCommand在一个连接上与多个调用异步地调用存储过程。

每隔半秒就会在计时器上触发一次调用,并且在某些时间段内,我收到的结果与预期的一样,有时会收到以下错误:

System.Data.SqlClient.SqlException(0x80131904):当前命令发生严重错误。 结果(如果有的话)应丢弃。
在System.Data.SqlClient.SqlConnection.OnError(SqlException异常,Boolea n breakConnection)
在System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception,Boolean breakConnection)
在System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
在System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior,SqlCommand cm dHandler,SqlDataReader dataStream,BulkCopySimpleResultSet bulkCopyHandler,Tds ParserStateObject stateObj)
在System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
在System.Data.SqlClient.SqlDataReader.get_MetaData()
在System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,运行行为runBehavior,字符串resetOptionsString)
在System.Data.SqlClient.SqlCommand.CompleteAsyncExecuteReader()
在System.Data.SqlClient.SqlCommand.InternalEndExecuteReader(IAsyncResult asy ncResult,String endMethod)
在System.Data.SqlClient.SqlCommand.EndExecuteReader(IAsyncResult asyncResult)

SQL日志反复显示以下错误:

服务器将断开连接,因为在会话处于单用户模式下时,客户端驱动程序已发送了多个请求。 当客户端在会话中仍在运行批处理时发出请求重置连接的请求时,或者当客户端在会话重置连接时发送请求时,将发生此错误。 请与客户端驱动程序供应商联系。

我的连接字符串具有MARS和Async = true设置。 尽管目标客户端将是成熟的SQL Server实例,但我目前正在使用SQL Server 2008 Express。

我创建了以下控制台应用程序,该应用程序在我的计算机上表现出相同的行为,我创建的DummySp刚一被调用就返回

public class BusinessObject
{
    public string  Name {get; set;}
    public void UpdateData(DataTable dataTable)
    {
        Console.WriteLine("{0}: new data received.",Name);
    }
}

public class Program
{
    private const string SpName = "DummySp";
    private const string ConnectionsString = @"Data Source=(local)\sqlexpress;Initial Catalog=Test;Integrated Security=SSPI;Connection Timeout=3600";

    private static readonly object DbRequestLock = new object();
    private static readonly ManualResetEvent DatabaseRequestsComplete = new ManualResetEvent(false);
    private static int _databaseRequestsLeft;
    private static Timer _timer;

    static readonly List<BusinessObject> BusinessObjects = new List<BusinessObject>
    {
        new BusinessObject{Name = "A"},
        new BusinessObject{Name = "B"},
        new BusinessObject{Name = "C"},
    };

    static void Main(string[] args)
    {
        _timer = new Timer(DoQuery, null, 0, 500);

        Console.ReadLine();

        _timer.Dispose();         
    }

    private static void DoQuery(object state)
    {
        try
        {
           lock (DbRequestLock)
            {

                DatabaseRequestsComplete.Reset();
                _databaseRequestsLeft = BusinessObjects.Count;

                var builder = new SqlConnectionStringBuilder(ConnectionsString)
                    {
                        AsynchronousProcessing = true,
                        MultipleActiveResultSets = true
                    };

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

                    foreach (var businessObject in BusinessObjects)
                    {
                        var command = new SqlCommand(SpName, connection) { CommandType = CommandType.StoredProcedure };

                        command.BeginExecuteReader(Callback, new Tuple<SqlCommand, BusinessObject>(command, businessObject));
                    }

                    // need to wait for all to complete before closing the connection
                    DatabaseRequestsComplete.WaitOne(10000);
                    connection.Close();
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Following error occurred while attempting to update objects: " + ex);
        }
    }

    private static void Callback(IAsyncResult result)
    {
        try
        {
            var tuple = (Tuple<SqlCommand, BusinessObject>)result.AsyncState;
            var businessObject = tuple.Item2;

            using (SqlCommand command = tuple.Item1)
            {
                using (SqlDataReader reader = command.EndExecuteReader(result))
                {
                    using (var table = new DataTable(businessObject.Name))
                    {
                        table.Load(reader);

                        businessObject.UpdateData(table);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
        finally
        {
            // decrement the number of database requests remaining and, if there are 0 fire the mre
            if (Interlocked.Decrement(ref _databaseRequestsLeft) == 0)
            {
                DatabaseRequestsComplete.Set();
            }
        }
    }
}

关于如何克服这一点的任何想法?

谢谢

这不是直接回答我的问题,因此我没有将其标记为此类,但是我认为值得展示每个对象具有单个连接的替​​代方法,因为这似乎可以避免问题的发生...

 private static void DoQuery(object state)
    {
        try
        {
            lock (DbRequestLock)
            {

                var builder = new SqlConnectionStringBuilder(ConnectionsString)
                    {
                        AsynchronousProcessing = true,
                    };

                DatabaseRequestsComplete.Reset();
                _databaseRequestsLeft = BusinessObjects.Count;

                foreach (var businessObject in BusinessObjects)
                {
                    var newConnection = new SqlConnection(builder.ConnectionString);
                    newConnection.Open();

                    var command = new SqlCommand(SpName, newConnection) { CommandType = CommandType.StoredProcedure };

                    command.BeginExecuteReader(Callback, new Tuple<SqlCommand, BusinessObject>(command, businessObject),CommandBehavior.CloseConnection);

                }
                // need to wait for all to complete                    DatabaseRequestsComplete.WaitOne(10000);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Following error occurred while attempting to update objects: " + ex);
        }
    }

    private static void Callback(IAsyncResult result)
    {
        var tuple = (Tuple<SqlCommand, BusinessObject>)result.AsyncState;
        var businessObject = tuple.Item2;
        SqlCommand command = tuple.Item1;
        try
        {
            using (SqlDataReader reader = command.EndExecuteReader(result))
            {
                using (var table = new DataTable(businessObject.Name))
                {
                    table.Load(reader);

                    businessObject.UpdateData(table);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
        finally
        {
            // decrement the number of database requests remaining and, if there are 0 fire the mre
            if (Interlocked.Decrement(ref _databaseRequestsLeft) == 0)
            {
                DatabaseRequestsComplete.Set();
            }

            try
            {
                command.Dispose();
                command.Connection.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM