防止同一范围内,异步执行事务误触非当前线程事务

This commit is contained in:
Linlccc 2022-02-26 14:39:05 +08:00
parent c0b6a75c79
commit 3ba865704a

View File

@ -8,9 +8,12 @@ namespace Blog.Core.Repository.UnitOfWork
{
private readonly ISqlSugarClient _sqlSugarClient;
private int _tranCount { get; set; }
public UnitOfWork(ISqlSugarClient sqlSugarClient)
{
_sqlSugarClient = sqlSugarClient;
_tranCount = 0;
}
/// <summary>
@ -25,25 +28,40 @@ namespace Blog.Core.Repository.UnitOfWork
public void BeginTran()
{
GetDbClient().BeginTran();
lock (this)
{
_tranCount++;
GetDbClient().BeginTran();
}
}
public void CommitTran()
{
try
lock (this)
{
GetDbClient().CommitTran(); //
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
GetDbClient().RollbackTran();
_tranCount--;
if (_tranCount == 0)
{
try
{
GetDbClient().CommitTran();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
GetDbClient().RollbackTran();
}
}
}
}
public void RollbackTran()
{
GetDbClient().RollbackTran();
lock (this)
{
_tranCount--;
GetDbClient().RollbackTran();
}
}
}