Skip to content

Commit 8312999

Browse files
authored
Merge pull request anjoy8#248 from Linlccc/master
防止同一范围内,异步执行事务误触非当前线程事务
2 parents d567aea + 3ba8657 commit 8312999

1 file changed

Lines changed: 27 additions & 9 deletions

File tree

Blog.Core.Repository/UnitOfWork/UnitOfWork.cs

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,12 @@ public class UnitOfWork : IUnitOfWork
88
{
99
private readonly ISqlSugarClient _sqlSugarClient;
1010

11+
private int _tranCount { get; set; }
12+
1113
public UnitOfWork(ISqlSugarClient sqlSugarClient)
1214
{
1315
_sqlSugarClient = sqlSugarClient;
16+
_tranCount = 0;
1417
}
1518

1619
/// <summary>
@@ -25,25 +28,40 @@ public SqlSugarScope GetDbClient()
2528

2629
public void BeginTran()
2730
{
28-
GetDbClient().BeginTran();
31+
lock (this)
32+
{
33+
_tranCount++;
34+
GetDbClient().BeginTran();
35+
}
2936
}
3037

3138
public void CommitTran()
3239
{
33-
try
40+
lock (this)
3441
{
35-
GetDbClient().CommitTran(); //
36-
}
37-
catch (Exception ex)
38-
{
39-
Console.WriteLine(ex.Message);
40-
GetDbClient().RollbackTran();
42+
_tranCount--;
43+
if (_tranCount == 0)
44+
{
45+
try
46+
{
47+
GetDbClient().CommitTran();
48+
}
49+
catch (Exception ex)
50+
{
51+
Console.WriteLine(ex.Message);
52+
GetDbClient().RollbackTran();
53+
}
54+
}
4155
}
4256
}
4357

4458
public void RollbackTran()
4559
{
46-
GetDbClient().RollbackTran();
60+
lock (this)
61+
{
62+
_tranCount--;
63+
GetDbClient().RollbackTran();
64+
}
4765
}
4866

4967
}

0 commit comments

Comments
 (0)