【问题标题】:Why inner TransactionScope's IsolationLevel cannot be different, while SQL transactions can be?为什么内部 TransactionScope 的 IsolationLevel 不能不同,而 SQL 事务可以?
【发布时间】:2020-05-09 10:44:44
【问题描述】:

在数据库事务中更改隔离级别是可以的,包括将一个事务加入到已经运行的事务的情况。 从现在开始,您只需更改处理锁的方式。使用 Sql Server,运行没有问题:

begin transaction 
set transaction isolation level serializable;
select * from FooTable;

set transaction isolation level read committed;
select * from FooTable;

begin transaction
set transaction isolation level serializable;
select * from FooTable;
--transaction_isolation_level can be observed as 4 (serializable)

但是,当使用 .NET TransactionScope 在上述 Sql Server 中创建事务时,像这样(C#,xUnit):

[Theory]
[AutoFixtureMagicToGetParameterInstances]
void ZmenaIzolacniUrovneVedeKVyjimce(IFooDao sut, Foo foo)
{
    var tranOpts = new TransactionOptions()
    {
        IsolationLevel = IsolationLevel.Serializable,
        Timeout = TimeSpan.FromSeconds(60)
    };
    var tranOpts2 = new TransactionOptions()
    {
        IsolationLevel = IsolationLevel.ReadCommitted,
        Timeout = TimeSpan.FromSeconds(60)
    };
    using (var transactionScope = new TransactionScope(TransactionScopeOption.Required, tranOpts))
    {
        sut.SelectFoos();
        using (var transactionScope2 = new TransactionScope(TransactionScopeOption.Required, tranOpts2))
        {
            sut.SelectFoos();
        }
    }
}

导致异常:

System.ArgumentException : The transaction specified for TransactionScope has a different IsolationLevel than the value requested for the scope.
 Parameter name: transactionOptions.IsolationLevel

为什么 TransactionScope 的设计者认为有必要立即抛出异常?

我希望至少只要只涉及数据库资源,行为就会相同。 是否有一些关于 TransactionScope 的内容我遗漏了,或者仅仅是因为无法保证所有可能的征募资源的合理行为?

【问题讨论】:

  • 并非如此。这几乎是同一个问题 - 所以我很抱歉,我应该进行更多搜索,我希望这样的问题能够提及异常的独特部分。但是也没有回答“为什么可以在这里改变隔离级别而不在那里”(正如 OP 在评论中指出的那样):( 所以不,它并没有真正回答它。
  • 我将其标记为重复问题。 “这个答案是否”是堆栈溢出的一部分在标记重复问题时更新自动评论文本
  • 我明白了。现在我注意到可接受的答案在可接受的答案下方的评论中 - 这并不比我在问题的最后一段中指出的更多,但我想没有人会添加更多内容。我想我应该对我的问题投票并在那里编辑答案,以便下次更明显?
  • 再想一想,我的问题略有不同,更多的是针对“为什么存在差异” - 我会在这里进行适当的编辑。

标签: c# transactions transactionscope


【解决方案1】:

如 cmets 中所述Inner TransactionScope with different IsolationLevel, how can it be achieved?

TransactionScope 不限于与 SQL Server 一起使用,它可以允许 跨进程/系统的分布式事务。所以更严格 超出 SQL Server 允许的范围,可能会简化 确保跨系统的一致性而不是支持分布式 交易。 – 亚伦LS

所以答案基本上似乎归结为“TransactionScope可能在它的盘子上不仅仅是数据库事务,因此它禁止更改隔离级别等复杂性”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    相关资源
    最近更新 更多