我目前对 TransactionScope 对象的构造函数感到困惑。
假设我网站的用户可以订购产品。提交请求后,我会验证当前剩余数量,如果仍然大于零,我就会执行该请求。然后,最后我减少当前剩余数量。
整个过程都在一个事务内,使用 .NET transactionScope。
阅读了几篇有关 .NET transactionScope 对象的文章后,我现在对用于 transactionScope 构造函数的 TransactionScopeOption 的值有点困惑。
以下哪一项更适合上述情况:
public void ProcessRequest()
{
TransactionOptions transactionOptions = new TransactionOptions();
transactionOptions.IsolationLevel = IsolationLevel.Serializable;
using (TransactionScope currentScope = new TransactionScope(TransactionScopeOption.RequiresNew, transactionOptions)) {
// DB Query to verify if quantity is still greater than zero
// DB Query to request and decrement quantity
currentScope.Complete();
}
}
或
public void ProcessRequest()
{
TransactionOptions transactionOptions = new TransactionOptions();
transactionOptions.IsolationLevel = IsolationLevel.Serializable;
using (TransactionScope currentScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions)) {
// DB Query to verify if quantity is still greater than zero
// DB Query to request and decrement quantity
currentScope.Complete();
}
}
请注意,以上只是我的实际问题的过度简化。我只想知道这种情况下 TransactionScopeOption 的正确值(RequiresNew 或 Required)。
感谢您的回复。
最佳答案
如果另一个方法在另一个事务内调用ProcessRequest
,这取决于您希望发生的情况:
public void SomeOtherMethod() {
using (TransactionScope ts = new TransactionScope()) {
// Another DB action
ProcessRequest();
// Yet another DB action
}
}
如果您希望 ProcessRequest
使用 SomeOtherMethod
创建的事务,请使用 TransactionScope.Required
。这是默认设置(当您调用它时,它仍然会创建一个事务,而无需在调用堆栈上创建另一个事务范围)。
如果您希望强制此方法始终使用自己的(新)事务,请使用 TransactionScope,RequiresNew
。
关于.net - TransactionScopeOption - 必需或 RequiresNew,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4629245/