问题描述
据我了解,使用TransactionScope
的正确"方法是在退出using
块之前始终调用transactionScope.Complete();
.像这样:
As far as I understand, the "correct" way to use a TransactionScope
is to always call transactionScope.Complete();
before exiting the using
block. Like this:
using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted }))
{
//...
//I'm using this as a NOLOCK-alternative in Linq2sql.
transactionScope.Complete();
}
但是,我发现没有它,代码就可以工作,甚至我从中学到的使用它的答案忽略它.所以我的问题是,是否必须使用它?
However, I've seen that the code works without it, and even the answer I've learnt to use it from omits it. So my question is, must it be used or not?
推荐答案
为了进行COMMIT
交易而进行更新时必须使用
Complete
.否则,事务管理器将发出ROLLBACK
并撤消所做的更改.
Complete
must be used when updates are made in order to COMMIT
the transaction. Otherwise, the transaction manger will issue a ROLLBACK
and undo changes made.
对于像您的示例这样的只读事务,无论是否使用Complete
,我都认为没有实质性区别.在这两种情况下,事务管理器发出的COMMIT
或ROLLBACK
具有释放事务持有的锁和资源的相同净效果.
With a read-only transaction like your example, I can think of no material difference with or without Complete
. The COMMIT
or ROLLBACK
issued by the transaction manager will have the same net effect of releasing locks and resources held by the transaction in both cases.
尽管不是必需在只读事务中调用Complete
,但它仍然是IMHO的最佳实践.考虑一下这个可怜的开发人员,该开发人员后来在不知不觉中缺少Complete
的情况下,无意中将数据修改代码添加到了您的事务块中.
Although it's not a requirement to invoke Complete
in a read-only transaction, it's still a best practice IMHO. Consider the poor developer who later unwittingly adds data modification code to your transaction block without seeing Complete
is missing.
这篇关于我是否需要"transactionScope.Complete();"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!