Skip to content

Commit

Permalink
使用 KeyedLocker 避免锁字符串造成的锁定失败问题
Browse files Browse the repository at this point in the history
  • Loading branch information
Soar360 committed Sep 3, 2024
1 parent 117ad4d commit eea309c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
29 changes: 29 additions & 0 deletions XCode/Common/KeyedLocker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XCode.Common;

/// <summary>
/// 基于键的锁定器
/// </summary>
internal class KeyedLocker<TEntity>
{
private static object[] Lockers;
static KeyedLocker()
{
int Length = 8;
var temp = new object[Length];
for (int i = 0; i < Length; i++) temp[i] = new object();
Lockers = temp;
}

public static object SharedLock(string key)
{
if (key is null) throw new ArgumentNullException(nameof(key));
var code = key.GetHashCode();
return Lockers[Math.Abs(code % Lockers.Length)];
}
}
6 changes: 2 additions & 4 deletions XCode/Entity/Entity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2046,8 +2046,7 @@ public static TEntity GetOrAdd<TKey>(TKey key, Func<TKey, Boolean, TEntity?> fin
if (entity != null) return entity;

// 加锁,避免同一个key并发新增
var keyLock = $"{typeof(TEntity).FullName}-{key}";
lock (keyLock)
lock (KeyedLocker<TEntity>.SharedLock(key!.ToString()))
{
// 打开事务,提升可靠性也避免读写分离造成数据不一致
using var trans = Meta.CreateTrans();
Expand Down Expand Up @@ -2096,8 +2095,7 @@ public static TEntity GetOrAdd<TKey>(TKey key, Func<TKey, TEntity?> find, Func<T
if (entity != null) return entity;

// 加锁,避免同一个key并发新增
var keyLock = $"{typeof(TEntity).FullName}-{key}";
lock (keyLock)
lock (KeyedLocker<TEntity>.SharedLock(key!.ToString()))
{
// 打开事务,提升可靠性也避免读写分离造成数据不一致
using var trans = Meta.CreateTrans();
Expand Down

0 comments on commit eea309c

Please sign in to comment.