Noah Mt4跟单系统制作第十篇 锁篇

試著忘記壹切 提交于 2021-02-18 16:43:53
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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!