using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Copier.Core
{
public sealed class KeyLocker<T> : IDisposable
{
private static readonly object _lockerDictionary = new object();
private static readonly Dictionary<T, LockerObject> _lockerObjects = new Dictionary<T, LockerObject>();
private T _key;
public KeyLocker(T key)
{
_key = key;
LockerObject lockerObject;
lock (_lockerDictionary)
{
if (!_lockerObjects.TryGetValue(_key, out lockerObject))
{
lockerObject = new LockerObject();
_lockerObjects.Add(_key, lockerObject);
}
lockerObject.Count++;
}
Monitor.Enter(lockerObject);
}
public void Dispose()
{
lock (_lockerDictionary)
{
LockerObject lockerObject = _lockerObjects[_key];
lockerObject.Count--;
if (lockerObject.Count == 0)
_lockerObjects.Remove(_key);
Monitor.Exit(lockerObject);
}
}
private sealed class LockerObject
{
public int Count;
}
}
}
NoahWork
来源:oschina
链接:https://my.oschina.net/u/4992230/blog/4954837