Browse Source

增加 TextUtility.Lock,实现线程锁。

dev
王厅 2 months ago
parent
commit
d7e7304243
  1. 75
      Apewer/Internals/Locker.cs
  2. 26
      Apewer/TextUtility.cs

75
Apewer/Internals/Locker.cs

@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Apewer.Internals
{
/// <summary>锁。</summary>
internal class Locker
{
Dictionary<int, Class<object>> _pool = new Dictionary<int, Class<object>>();
/// <summary>标记指定的字符串。</summary>
static int Key(string s) => s == null ? 0 : s.GetHashCode();
/// <summary>清除所有缓存的锁。</summary>
public void Clear()
{
lock (_pool)
{
_pool.Clear();
}
}
/// <summary>锁定字符串,执行 Action。</summary>
public void InLock(string text, Action action)
{
if (action == null) return;
var key = Key(text);
Class<object> locker;
lock (_pool)
{
if (!_pool.TryGetValue(key, out locker))
{
locker = new Class<object>();
_pool.Add(key, locker);
}
}
lock (locker.Value)
{
action.Invoke();
}
}
/// <summary>锁定字符串,执行 Func。</summary>
public T InLock<T>(string text, Func<T> func)
{
if (func == null) return default;
var key = Key(text);
Class<object> locker;
lock (_pool)
{
if (!_pool.TryGetValue(key, out locker))
{
locker = new Class<object>();
_pool.Add(key, locker);
}
}
T result;
lock (locker.Value)
{
result = func.Invoke();
}
return result;
}
}
}

26
Apewer/TextUtility.cs

@ -1044,6 +1044,32 @@ namespace Apewer
return trim ? Trim(middle, trimBlank) : middle;
}
#region Lock
static Locker _locker = new Locker();
/// <summary>锁定文本,在锁中执行函数。</summary>
/// <param name="text">要锁定的文本。</param>
/// <param name="inLock">要在锁中执行的函数。</param>
/// <exception cref="ArgumentNullException"></exception>
public static T Lock<T>(this string text, Func<T> inLock)
{
if (inLock == null) throw new ArgumentNullException(nameof(inLock));
return _locker.InLock(text, inLock);
}
/// <summary>锁定文本,在锁中执行函数。</summary>
/// <param name="text">要锁定的文本。</param>
/// <param name="inLock">要在锁中执行的函数。</param>
/// <exception cref="ArgumentNullException"></exception>
public static void Lock<T>(this string text, Action inLock)
{
if (inLock == null) throw new ArgumentNullException(nameof(inLock));
_locker.InLock(text, inLock);
}
#endregion
#region encoding
/// <summary>检查字节数组包含 UTF-8 BOM 头。</summary>

Loading…
Cancel
Save