c# - SqlConnection 是如何管理 IsolationLevel 的?

标签 c# .net sql-server ado.net transactions

MSDN article指出:

An isolation level has connection-wide scope, and once set for a connection with the SET TRANSACTION ISOLATION LEVEL statement, it remains in effect until the connection is closed or another isolation level is set. When a connection is closed and returned to the pool, the isolation level from the last SET TRANSACTION ISOLATION LEVEL statement is retained. Subsequent connections reusing a pooled connection use the isolation level that was in effect at the time the connection is pooled.

SqlConnection类没有可能拥有隔离级别的成员。那么连接如何知道要在哪个隔离级别运行???

我问这个的原因是因为以下情况:

  1. 我使用 Serializable 中的 TransactionScope 模式,说“T1”。
  2. 为 T1 打开了一个连接。
  3. T1 完成/配置,连接 回到连接池。
  4. 调用了另一个相同的查询 连接(从 连接池)并且此查询运行 在可序列化模式下!!!

问题:

  1. 池连接如何仍然 知道隔离级别是什么 与之相关???
  2. 如何将其还原为其他 交易级别???

Resolution:
The reason why pooled connections are returning the serializable isolation level is because of the following reason:

  1. You have one connection pool (let's say CP1)
  2. CP1 may have 50 connections.
  3. You pick one connection C1 from CP1 and execute it with Serializable. This connection has its isolation level set now. Whatever you do, this will not be reset (unless this connection is used to execute a code in a different isolation level).
  4. After executing the query C1(Serializable) goes back to CP1.
  5. If steps 1-4 are executed again then the connection used may be some other connection than C1, let's say C2 or C3. So, that will also have its isolation level set to Serializable.
  6. So, slowly, Serialzable is set to multiple connections in CP1.
  7. When you execute a query where no explicit isolation level setting is being done, the connection picked from CP1 will decide the isolation level. For e.g. if such a query requests for a connection and CP1 uses C1(Serializable) to execute this query then this query will execute in Serializable mode even though you didn't explicitly set it.

Hope that clears a few doubts. :)

最佳答案

隔离级别在底层 DBMS 中实现,例如 SqlServer。设置隔离级别很可能会设置为连接设置隔离级别的 SQL 命令。

只要连接保持打开状态,DBMS 就会保持隔离级别。因为连接被放入池中,所以它保持打开状态并保留之前所做的设置。

当弄乱隔离级别时,您应该在任何事务结束时重置隔离级别,或者更好的是,在请求新连接时设置它。

关于c# - SqlConnection 是如何管理 IsolationLevel 的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3759897/

相关文章:

c# - 使用 java 和 WP7 进行 AES 加密

c# - 为更新面板编写代码触发器。 C#——ASP.NET

c# - 如何在 IComparer.Compare 方法上将 'object' 转换为类类型

c# - System.Reflection 没有方法

c# - 在 Code First Entity Framework (C# ASP.NET MVC 3) 中指定除 dbo 之外的 SQL 用户名

sql-server - 创建列存储索引

sql-server - SQL Server ORDER BY 日期和最后的空值

c# - DispatcherOperations.Wait()

c# - 如何获取文件夹的 NTFS 文件 ID

c# - Linq where in 子句