在这种情况下,我希望有这样的界面
using (SyncDispatcher.Enter(id))
{
//any code here...
}
所以我可以执行任何代码,如果 id 相同,它将是线程安全的。如果我需要从缓存中获取价值,我会直接得到它,因为没有并发调用。
我对 SyncDispatcher 的实现是这样的:
public class SyncDispatcher : IDisposable
{
private static object _lock = new object();
private static Dictionary<object, SyncDispatcher> _container = new Dictionary<object, SyncDispatcher>();
private AutoResetEvent _syncEvent = new AutoResetEvent(true);
private SyncDispatcher() { }
private void Lock()
{
_syncEvent.WaitOne();
}
public void Dispose()
{
_syncEvent.Set();
}
public static SyncDispatcher Enter(object obj)
{
var objDispatcher = GetSyncDispatcher(obj);
objDispatcher.Lock();
return objDispatcher;
}
private static SyncDispatcher GetSyncDispatcher(object obj)
{
lock (_lock)
{
if (!_container.ContainsKey(obj))
{
_container.Add(obj, new SyncDispatcher());
}
return _container[obj];
}
}
}
简单测试:
static void Main(string[] args)
{
new Thread(() => Execute("1", 1000, "Resource 1")).Start();
new Thread(() => Execute("2", 200, "Resource 2")).Start();
new Thread(() => Execute("1", 0, "Resource 1 again")).Start();
}
static void Execute(object id, int timeout, string message)
{
using (SyncDispatcher.Enter(id))
{
Thread.Sleep(timeout);
Console.WriteLine(message);
}
}