使用可选参数避免嵌套事务

时间:2017-10-31 20:34:30

标签: c# sql-server

我有两个函数Method1()和Method2()。这些方法中的每一个都在事务中

public void Method1() {
    using(TransactionScope scope = new TransactionScope()) {
       // Do Stuff
       scope.Complete()
    }
}

public void Method2() {
    using(TransactionScope scope = new TransactionScope()) {
       // Do Stuff 2
       scope.Complete()
    }
}

现在我正在尝试创建一个结合了method1和2的新方法,并且必须是原子方法。

 public void Method1and2() {
    using(TransactionScope scope = new TransactionScope()) {
        Method1();
        Method2();
        scope.Complete()
    }
 }

我希望它是全有或全无。我可以看到,

我有两个选择:    1.以这种方式复制没有Transaction(方法重载)的Method1()和Method2():

public void Method1() {
    using(TransactionScope scope = new TransactionScope()) {
       // Do Stuff
       scope.Complete()
    }
}

public void Method1(bool anything ) {
       // Do Stuff
}

或者我在Method1和Method2中使用可选参数:

public void Method1(bool ignoreTransaction = false) {
        var typeTransaction = TransactionScopeOption.Required;

        if (ignoreTransaction)
            typeTransaction = TransactionScopeOption.Suppress;

    using(TransactionScope scope = new TransactionScope(typeTransaction)) {
       // Do Stuff
       scope.Complete()
    }
}

哪一个更好?

0 个答案:

没有答案