/// <summary>
        /// Acquires a read lock on both the block and the block collection.
        /// </summary>
        /// <param name="collectionLock">The lock on the block collection.</param>
        /// <param name="blockLock">The lock object used to acquire the lock.</param>
        /// <param name="requestLock"></param>
        public BlockLock(
			IDisposable collectionLock,
			ReaderWriterLockSlim accessLock,
			RequestLock requestLock)
        {
            // Keep track of the collection lock so we can release it.
            this.collectionLock = collectionLock;

            // Acquire the lock based on the requested type.
            switch (requestLock)
            {
                case RequestLock.Read:
                    blockLock = new NestableReadLock(accessLock);
                    break;

                case RequestLock.UpgradableRead:
                    blockLock = new NestableUpgradableReadLock(accessLock);
                    break;

                case RequestLock.Write:
                    blockLock = new NestableWriteLock(accessLock);
                    break;

                default:
                    throw new InvalidOperationException(
                        "Could not acquire lock with unknown type: " + requestLock);
            }
        }
        public void Dispose_Errors()
        {
            var v = new ReaderWriterLockSlim();
            v.Dispose();

            try
            {
                v.EnterUpgradeableReadLock();
                Assert.Fail("1");
            }
            catch (ObjectDisposedException)
            {
            }

            try
            {
                v.EnterReadLock();
                Assert.Fail("2");
            }
            catch (ObjectDisposedException)
            {
            }

            try
            {
                v.EnterWriteLock();
                Assert.Fail("3");
            }
            catch (ObjectDisposedException)
            {
            }
        }
Example #3
0
 public Topic(uint storeSize, TimeSpan lifespan)
 {
     _lifespan = lifespan;
     Subscriptions = new List<ISubscription>();
     Store = new MessageStore<Message>(storeSize);
     SubscriptionLock = new ReaderWriterLockSlim();
 }
Example #4
0
        public Region(int id)
        {
            _creaturesRWLS = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
            _propsRWLS = new ReaderWriterLockSlim();
            _itemsRWLS = new ReaderWriterLockSlim();

            this.Id = id;

            _creatures = new Dictionary<long, Creature>();
            _props = new Dictionary<long, Prop>();
            _items = new Dictionary<long, Item>();

            _clients = new HashSet<ChannelClient>();

            _regionData = AuraData.RegionInfoDb.Find(this.Id);
            if (_regionData == null)
            {
                Log.Warning("Region: No data found for '{0}'.", this.Id);
                return;
            }

            this.Collissions = new RegionCollision(_regionData.X1, _regionData.Y1, _regionData.X2, _regionData.Y2);
            this.Collissions.Init(_regionData);

            this.LoadClientProps();
        }
Example #5
0
		public DefaultNodeLocator()
		{
			this.servers = new Dictionary<uint, IMemcachedNode>(new UIntEqualityComparer());
			this.deadServers = new Dictionary<IMemcachedNode, bool>();
			this.allServers = new List<IMemcachedNode>();
			this.serverAccessLock = new ReaderWriterLockSlim();
		}
Example #6
0
File: Rider.cs Project: Cycli/Cycli
 public Rider()
 {
     _outputDatum = new InterfaceDatum();
     _datumLock = new ReaderWriterLockSlim();
     _IsSent = true; // This will prevent any send until new data are available
     _rnd = new Random();        // For test data
 }
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    //free managed resources here
                }

                //free unmanaged resrources here
                if (_lock.IsReadLockHeld)
                {
                    _lock.ExitReadLock();
                }
                else if (_lock.IsWriteLockHeld)
                {
                    _lock.ExitWriteLock();
                }
                else if (_lock.IsUpgradeableReadLockHeld)
                {
                    _lock.ExitUpgradeableReadLock();
                }

                _lock = null;
                _disposed = true;
            }
        }
        public MorphologicalFilteringOptionsViewModel()
        {
            StackSync = new ReaderWriterLockSlim();

            if (Execute.InDesignMode)
                LoadDesignTimeData();
        }
        public NntpParser(NzbConnection connection)
        {
            ArgumentChecker.ThrowIfNull("connection", connection);

            _connection = connection;
            _synchronizationObject = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
        }
Example #10
0
        protected int timerPerion; // частота отрисовки графиков в активном режиме

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Инициализирует новый экземпляр класса
        /// </summary>
        /// <param name="GPanel">Панель которую будет обслуживать манеджер</param>
        public GraphicManager(Panel GPanel)
        {
            mutex = new Mutex();
            slim = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);

            mode = DrawMode.Default;

            if (GPanel != null)
            {
                panel = GPanel;
                //panel.StartTime = DateTime.Now;

                panel.OnResize += new EventHandler(Sheet_Resize);

                panel.Sheet.onOrientationChange += new EventHandler(Sheet_onOrientationChange);
                panel.Sheet.onIntervalInCellChange += new EventHandler(Sheet_onIntervalInCellChange);

                timerPerion = 500;
                timer = new Timer(TimerCallback, null, Timeout.Infinite, timerPerion);
            }
            else
            {
                throw new ArgumentNullException();
            }
        }
Example #11
0
        protected List<Place> places = null; // место в репозитарии

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Инициализирует новый экземпляр класса
        /// </summary>
        public Repository()
        {
            mutex = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);

            places = new List<Place>();
            packets = new List<Packet>();
        }
Example #12
0
		public ServiceHost(int servicePort)
		{
			pools = new List<SocketPool>();
			poolsLock = new ReaderWriterLockSlim();
			container = new ServiceContainer();
			this.servicePort = servicePort;
		}
 public void Dispose()
 {
     if (_sync != null) {
         _sync.ExitWriteLock();
         _sync = null;
     }
 }
Example #14
0
        public RideProcessor(string userId)
        {
            _outputLock = new ReaderWriterLockSlim();
            UserId = userId;
            // load the turbo
            _spotData = new Spot();
            _lastSpotData = null;

            // Set-up the lease

            LeaseId = GenerateLease(12);

            // Set the initial timeout
            LastUpdateTimestamp = DateTime.UtcNow;

            _messageQueue = new Queue<InterfaceDatum>(QUEUE_CAPACITY);
            _queueLock = new ReaderWriterLockSlim();
            _zeroingTimer = new Timer(CheckZeroing, null, 1000, 4000);

            _Rider = Rider.LoadAny(userId);

            // will load either a real or virtual rider
            if (_Rider != null)
            {
                _Turbo = TurboTrainer.Load(UserId, _Rider.CurrentTurbo, _Rider.TurboIsCalibrated);
            }
        }
Example #15
0
 public SafeReaderWriterLock()
 {
     this.locker = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
     this.upgradableReaderLock = new SafeUpgradeReaderLock(this.locker);
     this.readerLock = new SafeReaderLock(this.locker);
     this.writerLock = new SafeWriterLock(this.locker);
 }
Example #16
0
 public DbDiskCache(IFileWrapper fileWrapper, IRRConfiguration configuration, IUriBuilder uriBuilder) : base(fileWrapper, configuration, uriBuilder, null)
 {
     RRTracer.Trace("Creating db disk cache");
     const int interval = 1000*60*5;
     timer = new Timer(PurgeOldFiles, null, 0, interval);
     _cacheLock = new ReaderWriterLockSlim();
 }
        internal PacketReceiver(string LocalAddress) : base (LocalAddress)
        {
            packetReceiver = new Queue();
            tokenSource = new CancellationTokenSource();
            readerWriterLock = new ReaderWriterLockSlim();

            tokenSource.Token.Register(() => { 
                // Clear on cancel
                packetReceiver.Clear(); 
            });


            var thReceiveQueue = Task.Factory.StartNew(() => {
                while (tokenSource.Token.IsCancellationRequested == false)
                {
                    readerWriterLock.EnterUpgradeableReadLock();
                    if (packetReceiver.Count > 0)
                    {
                        readerWriterLock.EnterWriteLock();

                        byte[] data = (byte[])packetReceiver.Dequeue();

                        readerWriterLock.ExitWriteLock();

                        if (OnNewPacketReceived != null)
                            OnNewPacketReceived(this, new NewPacketEventArgs(data));
                    }

                    readerWriterLock.ExitUpgradeableReadLock();
                }
            });

        }
 public void Dispose()
 {
     if (IsDisposed)
         throw new ObjectDisposedException(ToString());
     _readerWriterLock.ExitWriteLock();
     _readerWriterLock = null;
 }
Example #19
0
 public MysqlDatabase(DatabaseConfig config)
 {
     Connected = false;
     Connection = null;
     DatabaseLock = new ReaderWriterLockSlim();
     Connect(config);
 }
Example #20
0
        // Private constructor to prevent explicit instantiation
        private Hub()
        {
            flows = new List<Flow>();
            subscriptions = new Dictionary<string, List<Flow>>();

            rwlock = new ReaderWriterLockSlim();
        }
Example #21
0
        public BaseSocketConnectionHost(HostType hostType, CallbackThreadType callbackThreadtype, ISocketService socketService, DelimiterType delimiterType, byte[] delimiter, int socketBufferSize, int messageBufferSize, int idleCheckInterval, int idleTimeOutValue)
        {
            context = new SocketProviderContext
            {
                Active = false,
                SyncActive = new object(),
                SocketCreators = new List<BaseSocketConnectionCreator>(),
                SocketConnections = new Dictionary<long, BaseSocketConnection>(),
                BufferManager = BufferManager.CreateBufferManager(0, messageBufferSize),
                SocketService = socketService,
                IdleCheckInterval = idleCheckInterval,
                IdleTimeOutValue = idleTimeOutValue,
                CallbackThreadType = callbackThreadtype,
                DelimiterType = delimiterType,
                Delimiter = delimiter,
                DelimiterEncrypt = new byte[] { 0xFE, 0xDC, 0xBA, 0x98, 0xBA, 0xDC, 0xFE },
                MessageBufferSize = messageBufferSize,
                SocketBufferSize = socketBufferSize,
                HostType = hostType
            };

            fSocketConnectionsSync = new ReaderWriterLockSlim();
            fWaitCreatorsDisposing = new ManualResetEvent(false);
            fWaitConnectionsDisposing = new ManualResetEvent(false);
            fWaitThreadsDisposing = new ManualResetEvent(false);
        }
Example #22
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="T:Stumps.Server.StumpsServerInstance"/> class.
        /// </summary>
        /// <param name="serverFactory">The factory used to initialize new server instances.</param>
        /// <param name="serverId">The unique identifier of the Stumps server.</param>
        /// <param name="dataAccess">The data access provider used by the instance.</param>
        public StumpsServerInstance(IServerFactory serverFactory, string serverId, IDataAccess dataAccess)
        {
            if (serverFactory == null)
            {
                throw new ArgumentNullException("serverFactory");
            }

            _serverFactory = serverFactory;

            this.ServerId = serverId;

            _lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
            _dataAccess = dataAccess;

            // Setup the objects needed to keep track of Stumps.
            _stumpList = new List<StumpContract>();
            _stumpReference = new Dictionary<string, StumpContract>(StringComparer.OrdinalIgnoreCase);

            // Setup the recordings maintained by the server instance.
            this.Recordings = new Recordings();

            // Initialize the server
            InitializeServer();

            // Initialize the Stumps
            InitializeStumps();
        }
Example #23
0
 /// <summary>
 /// 默认构造
 ///     没有更新间隔
 /// </summary>
 /// <param name="name"></param>
 public SrcUrlGroupTimer(string name)
 {
     this.name = name;
     this.intervalseconds = -1;
     this.listISU = new Dictionary<string, ISrcUrl>();
     this.thisLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
 }
Example #24
0
        private ReaderWriterLockSlim thisLock; //读写锁

        #endregion Fields

        #region Constructors

        public AqiManage()
        {
            thisLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);

            allDLLs = new List<Assembly>();
            InitDll();

            allAqiWebs = new Dictionary<string, IAqiWeb>();
            InitAqiWeb();

            allSrcUrls = new Dictionary<string, ISrcUrl>();
            InitSrcUrl();

            initSaver();
            //aqiSaver = new AqiFileSaver(this);
            aqiNoter = new AqiNoter(this);

            //目前默认为一个Retryer
            aqiRetryer = new AqiRetryer(this);

            initRunner();

            //目前默认为一个Runner
            //aqiRunner = new AqiRunner(this, allSrcUrls);
            //aqiRunner.RunEvent += new AqiRunner.RunEventHandler(aqiRunner_RunEvent);
        }
 public SimpleSubscriber()
 {
     _handlersStore = new Dictionary<Type, ISet<object>>();
     _emptySet = new object[0];
     _latch = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
     _typesCache = new Dictionary<Type, Type[]>();
 }
Example #26
0
        protected TypePort t_port = TypePort.Primary; // тип порта

        #endregion Fields

        #region Constructors

        /// <summary>
        /// инициализирует новый экземпляр класса
        /// </summary>
        public Serial(Repository reposit)
        {
            t_mutex = new Mutex();
            answerWaiter = new ManualResetEvent(true);

            timer = new Timer(TimerElapsed, null, Timeout.Infinite, timerPerion);

            //static_list = new List<Packet>();

            s_mutex = new Mutex();

            port = new SerialPort();
            passive_mutex = new Mutex();

            calculator = new CalculaterCRC();
            translater = new Translater(TranslaterFunction);

            input = new List<byte>();
            output = new List<byte>();

            opt_slim = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);

            attemptsToRead = 1;
            attemptsCycled = 128;

            waitTimeout = 20;
            repository = reposit;

            is_primary_done = false;
            is_secondary_done = false;

            is_slim = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
        }
Example #27
0
        internal HMDManager(IFactory factory, IDeviceManager manager)
        {
            if (factory == null)
                throw new ArgumentNullException();

            if (manager == null)
                throw new ArgumentNullException();

            _factory = factory;
            _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
            _manager = manager;
            _handler = new InternalMessageHandler(this);
            _manager.MessageHandler = _handler;
            _nativeResources = new Dictionary<DeviceKey, DeviceResources>();
            _devices = new Dictionary<DeviceKey, HMD>();
            _defaultprofile = manager.DeviceDefaultProfile;

            // Initially, we must to enumerate all devices, which are currently attached
            // to the computer.
            using (var handles = _manager.HMDDevices)
            {
                foreach (var handle in handles)
                {
                    AddDevice(handle);
                }
            }
        }
Example #28
0
 public ObjectVersionStore(Config config, ObjectMetadataStore metadata)
 {
     _metadata = metadata;
     _store = new KeyValueStore(Path.Combine(config.BaseDataPath, "ObjectVersionStore"));
     _versions = new Dictionary<string, uint>(StringComparer.OrdinalIgnoreCase);
     _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
 }
        private SlimThreadLockHandler(ReaderWriterLockSlim lockInstance, bool isWriteLock, bool blocking)
        {
            this.lockInstance = lockInstance;
            this.isWriteLock = isWriteLock;

            this.Enter(blocking);
        }
Example #30
0
        /// <summary>
        /// Executed ASYNCHRONOUSLY, 
        /// Allows to do a given action (in a new task) every XXX ms for XXX times
        /// by default it does the action when creating this instance, set doActionOnCreate = false to not do it immediatly
        /// </summary>
        public ReccurentAction(Action actionToDo, long timeLapse, int nbRepeat = 0, bool doActionOnCreate = true)
        {
            _nbRepeat = nbRepeat;
            _actionToDo = actionToDo;
            _lock = new ReaderWriterLockSlim();

            if (_actionToDo == null)
                throw new Exception("ReccurentAction > the action can't be null");

            // initiate the timer if needed
            if (_timer == null) {
                _timer = new Timer(timeLapse) {
                    AutoReset = true
                };
                _timer.Elapsed += OnTick;
                _timer.Start();
            }

            // do the recurrent action immediatly?
            if (doActionOnCreate)
                OnTick(null, null);

            // keep a reference to this so we can clean them all if needed
            _savedReccurentActionStarted.Add(this);
        }