谨慎使用TransactionScope,以防出现死锁
(2012-08-08 17:08:28)
标签:
杂谈 |
分类: 简单错误 |
近来在开发中涉及到调用已有的业务实现的dll,在做并发模拟的时候,很容易就出现deadlock。而且业务实现中对外公布的接口方法中使用了TransactionScope来管理事务。纠缠于此几天,今天做了一些模拟来一探究竟。
先创建一个用于测试的数据库表:
create table Customer(id int not null,
name nvarchar(50) not null,
primary key(id));
再插入两条数据:
insert into Customer
select 2,'0'
创建一个修改客户名称的类:
代码
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
public class
CustomerUpdater
{
public void Test(int customerId, string customerName)
{
TransactionOptions transactionOptions = new
TransactionOptions();
transactionOptions.IsolationLevel =
System.Transactions.IsolationLevel.Serializable;
using (TransactionScope txnScope = new
TransactionScope(TransactionScopeOption.Required,
transactionOptions,
EnterpriseServicesInteropOption.Automatic))
{
//read customer
Customer customer = getCustomer(customerId);
//update customer
if (customer != null)
{
updateCustomer(customer.Id, customer.Name + ":" +
customerName);
}
txnScope.Complete();
}
}
private string updateText = "update customer set name='{0}' where
id={1}";
private string selectText = "select * from customer where
id={0}";
先创建一个用于测试的数据库表:
create table Customer(id int not null,
name nvarchar(50) not null,
primary key(id));
再插入两条数据:
insert into Customer
select 2,'0'
创建一个修改客户名称的类:
代码
public class Customer

加载中…