繁体   English   中英

在 C#/ADO.NET 中为 SELECT 查询实现 SQL Server 2016 快照隔离

[英]Implement SQL Server 2016 Snapshot Isolation in C#/ADO.NET for SELECT queries

为了防止长时间读取操作在我现有的由 SQL Server 2016 支持的混合 OLTP/报告 Web 应用程序中阻塞短的、频繁的写入操作,我想对一些长时间运行的查询使用快照隔离。 查询已经被很好地索引,并且由于大量数据需要很长时间才能运行,虽然我以后可能会使用 RCSI,但我想从使用侵入性较小的快照隔离开始。

我的问题是:如何在 C# 中对 SELECT 查询启用快照隔离? 似乎我必须将我的选择查询包装在一个事务中,这感觉完全错误。

            List<Cat> cats = new List<Cat>();
            TransactionOptions transactionOption = new TransactionOptions
            {
                IsolationLevel = IsolationLevel.Snapshot
            };
            using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOption))
            {
                using (SqlConnection sqlConnection = new SqlConnection(databaseConnectionString))
                {
                    using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
                    {
                        sqlCommand.CommandText = "proc_Select_A_Billion_Cats";
                        sqlCommand.CommandType = CommandType.StoredProcedure;

                        sqlConnection.Open();

                        using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                        {
                            while (sqlDataReader.Read())
                            {
                                // SOME CODE HERE can read the Cat object in from data reader

                                // Add this cat to the collection
                                cats.Add(cat);
                            }
                        }
                    }
                }
            }

http://www.levibotelho.com/development/plugging-isolation-leaks-in-sql-server/我可以看到,在 SQL Server 2014 及更高版本中,当连接返回池时,隔离级别将被重置,所以这很好。

但是包装一个只在 ADO.NET 事务中执行 SELECT 的存储过程是否正确? 没有比这更好的方法来在 C# 中实现快照隔离了吗?

不,您需要在BeginTransaction方法中设置隔离级别

如果数据库已启用快照隔离但未配置为 READ_COMMITTED_SNAPSHOT ON,则必须在调用 BeginTransaction 方法时使用 IsolationLevel.Snapshot 枚举值启动 SqlTransaction。

否则,使用默认的Read Committed模式并且READ将被修改表的事务(可能)阻塞。

暂无
暂无

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

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