我在一个项目中采用三层结构,但在事务处理过程中发现存在一个问题,事务提交后就死锁了,示例代码如下:
public class test:IDisposable
{
private SqlDataAdapter dsCommand;
![]()
test()
{
dsCommand=new SqlDataAdapter()
dsCommand.InsertCommand=new SqlCommand();
dsCommand.InsertCommand.Connection=new SqlConnection("连接参数");
dsCommand.UpdateCommand=new SqlCommand();
dsCommand.UpdateCommand.Connection=new SqlConnection("连接参数");
dsCommand.DeleteCommand=new SqlCommand();
dsCommand.DeleteCommand.Connection=new SqlConnection("连接参数");
}
![]()
public void Update()
{
SqlTransaction trans=dsCommand.UpdateCommand.Connection.Transaction;
trans.BeginTransaction();
try
{
UpdateMaster(mastertable);
SaveDetail(detailtable);
trans.Commit();
}
catch
{
trans.RollBack();
![]()
}
}
![]()
private void SaveDetail(DataTable detailtable)
{
InsertDetail(detailtable);
UpdateDetail(detailtable);
DeleteDetail(detailtable);
}
private void InsertDetail(DataTable detailtable)
{
//使用插入存取过程
}
private void UpdateDetail(DataTable detailtable)
{
//使用修改存取过程
}
private void DeleteDetail(DataTable detailtable)
{
//使用删除存取过程
}
}死锁原因是为dsCommand中的每个SqlCommand创建了一个新的SqlConnection,需要做如下修改:
public class test:IDisposable
{
private SqlDataAdapter dsCommand;
private SqlConnection sqlconnection;
private SqlTransaction trans;
test()
{
dsCommand=new SqlDataAdapter()
sqlconnection=new SqlConnection("连接参数");
dsCommand.InsertCommand=new SqlCommand();
dsCommand.InsertCommand.Connection=sqlconnection;
dsCommand.UpdateCommand=new SqlCommand();
dsCommand.UpdateCommand.Connection=sqlconnection;
dsCommand.DeleteCommand=new SqlCommand();
dsCommand.DeleteCommand.Connection=sqlconnection;
}
![]()
public void Update()
{
if (sqlconnection.State!=ConnectionState.Open)
sqlconnection.Open();
trans=sqlconnection.Transaction;
trans.BeginTransaction();
try
{
UpdateMaster(mastertable);
SaveDetail(detailtable);
trans.Commit();
}
catch
{
trans.RollBack();
![]()
}
}
![]()
private void SaveDetail(DataTable detailtable)
{
InsertDetail(detailtable);
UpdateDetail(detailtable);
DeleteDetail(detailtable);
}
private void InsertDetail(DataTable detailtable)
{
//使用插入存取过程
}
private void UpdateDetail(DataTable detailtable)
{
//使用修改存取过程
}
private void DeleteDetail(DataTable detailtable)
{
//使用删除存取过程
}
}









































































































