这是正确的使用TransactionSope吗? [英] Is this correct usage of TransactionSope?
问题描述
我决定尝试使用 TransactionScope
,而不是 SqlTransaction
类。
以下是我的代码,包裹在 TransactionScope
:
using(var transaction = new System.Transactions.TransactionScope())
{
using(MySqlCommand cmd = new MySqlCommand(sql,connection))
{
if(listParameters!= null&& listParameters.Count> 0)
{
foreach(string currentKey in listParameters.Keys)
{
cmd.Parameters。 Add(new MySqlParameter(currentKey,GetDictionaryValue(listParameters,currentKey)));
}
}
使用(MySqlDataReader reader = cmd.ExecuteReader())
{
dtResults.Load(reader);
}
}
transaction.Complete();
}
代码工作,但是我不绑定 MySqlCommand
cmd
对象与任何时间的事务。这是一个问题吗?
不,这不是正确的用法。
正确的用法是在创建TransactionScope之后创建连接。然后,连接将检测周围的TransactionScope并征募自身。
using(var transaction = new System.Transactions.TransactionScope
{
using(var connection = new MySqlConnection())
{
...
}
}
如果在范围之前创建连接,那么该连接将超出范围,即使在创建范围后创建命令。 / p>
还要注意,TransactionScope默认为可串行化隔离级别。这是最安全的级别,但也是最少并发的级别。您通常希望显式地设置更常见的隔离级别:
using(var transaction = new TransactionScope(
TransactionScopeOption。必需,
new TransactionOptions(){IsolationLevel = IsolationLevel.ReadCommitted}))
{
}
I have decided to try using a TransactionScope
, rather than the SqlTransaction
class.
The following is my code, wrapped in a TransactionScope
:
using (var transaction = new System.Transactions.TransactionScope())
{
using (MySqlCommand cmd = new MySqlCommand(sql, connection))
{
if (listParameters != null && listParameters.Count > 0)
{
foreach (string currentKey in listParameters.Keys)
{
cmd.Parameters.Add(new MySqlParameter(currentKey, GetDictionaryValue(listParameters, currentKey)));
}
}
using (MySqlDataReader reader = cmd.ExecuteReader())
{
dtResults.Load(reader);
}
}
transaction.Complete();
}
The code works, however I am not binding the MySqlCommand
cmd
object with a transaction at any point. Is this a problem?
No, this is not the correct use.
The correct use is to create a connection after creating TransactionScope. Then the connection will detect the ambient TransactionScope and enlist itself.
using (var transaction = new System.Transactions.TransactionScope())
{
using (var connection = new MySqlConnection())
{
...
}
}
If you create the connection before the scope, that connection will be out of that scope, even if you create the command after creating the scope.
Also note that TransactionScope defaults to Serializable level of isolation. This is the most secure level, but also the least concurrent one. You often want to explicitly set a more common isolation level:
using (var transaction = new TransactionScope(
TransactionScopeOption.Required,
new TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted }))
{
}
这篇关于这是正确的使用TransactionSope吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!