public void OnRequestProcessed(int reqId)//, DealType side, string symbol)
 {
     try
     {
         locker.AcquireReaderLock(LockTimeout);
     }
     catch
     {
         return;
     }
     try
     {
         var index = requests.FindIndex(0, r => r.requestId == reqId);
         if (index < 0)
         {
             return;
         }
         locker.UpgradeToWriterLock(LockTimeout);
         requests.RemoveAt(index);
     }
     finally
     {
         locker.ReleaseLock();
     }
 }
Beispiel #2
0
 /// <summary>
 /// Stops the TCP Server listening for new clients and disconnects
 /// any currently connected clients.
 /// </summary>
 public void Stop()
 {
     tcpListener.Stop();
     try
     {
         lockClient.AcquireReaderLock(LockTimeout);
     }
     catch (Exception)
     {
         Logger.Error("TcpDistributor::Stop() - read timeout");
         return;
     }
     try
     {
         foreach (var client in clients)
         {
             client.TcpClient.Client.Disconnect(false);
         }
         try
         {
             lockClient.UpgradeToWriterLock(LockTimeout);
         }
         catch (Exception)
         {
             Logger.Error("TcpDistributor::Stop() - write timeout");
             return;
         }
         clients.Clear();
     }
     finally
     {
         lockClient.ReleaseLock();
     }
 }
        private static void WriteToFile(string contents, DateTime lastModified)
        {
            if (contents != null && contents.Length > 0)
            {
                blacklistReaderLock.AcquireWriterLock(250);

                try
                {
                    using (StreamWriter sw = File.CreateText(localPath))
                    {
                        sw.Write(contents);
                    }

                    File.SetCreationTimeUtc(localPath, lastModified);
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    blacklistReaderLock.ReleaseLock();
                }
            }
        }
 public void AssignExecutor(DelegateClosure <IExtendedSubject> executor)
 {
     try {
         _lockExecutor.AcquireWriterLock(-1);
         _clientExecutor = executor;
     }
     finally {
         _lockExecutor.ReleaseLock();
     }
 }
Beispiel #5
0
        public void addLab(String name)
        {
            mutex.AcquireWriterLock(60000);

            ClientNodeList tmp = new ClientNodeList(name);

            lab_list.Add(tmp);

            mutex.ReleaseLock();
        }
 public void AddRung(DelegatePredicate <ISubject> predicates, DelegateClosure <IExtendedSubject> executor)
 {
     try {
         _lockRung.AcquireWriterLock(-1);
         _rungs.Add(new Rung(predicates, executor));
     }
     finally {
         _lockRung.ReleaseLock();
     }
 }
Beispiel #7
0
 public void submitVerb(IVerb verb)
 {
     verbStateLock.AcquireWriterLock(Timeout.Infinite);
     //- If lock contention were an issue, we could accumulate these
     //- on a thread-local collection, then batch them into runnableVerbs
     //- during the lock inside scheduleAndWait.
     if (!startedVerbs.Contains(verb))
     {
         runnableVerbs.Add(verb);
     }
     verbStateLock.ReleaseLock();
 }
 private static void AddToList(object obj)
 {
     rwlock.AcquireWriterLock(1000);
     try
     {
         list.Add(obj);
     }
     finally
     {
         rwlock.ReleaseLock();
     }
 }
Beispiel #9
0
 public void Dispose()
 {
     _readerWriterLock.AcquireWriterLock(-1);
     try
     {
         _abort  = true;
         _socket = null;
     }
     finally
     {
         _readerWriterLock.ReleaseLock();
     }
 }
Beispiel #10
0
 public int Add(MessageFilter filter, IChannelListener listener)
 {
     try
     {
         _rwl.AcquireWriterLock(10000);
         _listeners.Add(filter, listener);
         return(_listeners.Count);
     }
     finally
     {
         _rwl.ReleaseLock();
     }
 }
Beispiel #11
0
        internal async void AddChangeEvent(string source, string whatKind)
        {
            string eventString = $"({DateTime.Now}) | File : {source} \t\t {whatKind}";

            FileEventsList.Add(eventString);
            try
            {
                IOLock.AcquireWriterLock(WriteTimeoutMs);
                await DataAccess.SetData(eventString);
            }
            finally
            {
                IOLock.ReleaseLock();
            }
        }
 public static void TrackReferrer(HttpRequest request, HttpServerUtility server)
 {
     readerLock.AcquireWriterLock(250);
     try
     {
         WriteReferrer(request, server);
     }
     catch
     {
     }
     finally
     {
         readerLock.ReleaseLock();
     }
 }
        /// <summary> Reloads if needed. </summary>
        /// <typeparam name="T">  </typeparam>
        /// <param name="rwLock"> The rw lock. </param>
        /// <param name="expires"> The expires. </param>
        /// <param name="interval"> The interval. </param>
        /// <param name="test"> The test. </param>
        /// <param name="reload"> The reload. </param>
        /// <returns> T. </returns>
        /// <exception cref="System.Exception">  </exception>
        public static T ReloadIfNeeded <T>(this ReaderWriterLock rwLock, ref DateTime expires,
                                           TimeSpan interval, Func <bool> test, Func <T> reload) where T : class
        {
            T   result = null;
            var now    = DateTime.Now;

            try
            {
                rwLock.AcquireReaderLock(90000);
                if (now >= expires)
                {
                    rwLock.UpgradeToWriterLock(90000);
                    if (now >= expires)
                    {
                        expires = now.Add(interval);
                        if (test == null || test())
                        {
                            result = reload();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                const string msg = "Unable to refresh value";
                throw new Exception(msg, e);
            }
            finally
            {
                rwLock.ReleaseLock();
            }
            return(result);
        }
Beispiel #14
0
        private static int GetBaseUnitIndex(string unitTypeName)
        {
            // Verify unitTypeName does not contain pipe char (which is used in serializations):
            if (unitTypeName.Contains('|'))
            {
                throw new ArgumentException("The name of a UnitType must not contain the '|' (pipe) character.", "unitTypeName");
            }

            // Lock baseUnitTypeNames:
            baseUnitTypeLock.AcquireReaderLock(2000);

            try
            {
                // Retrieve index of unitTypeName:
                int index = baseUnitTypeNames.IndexOf(unitTypeName);

                // If not found, register unitTypeName:
                if (index == -1)
                {
                    baseUnitTypeLock.UpgradeToWriterLock(2000);
                    index = baseUnitTypeNames.Count;
                    baseUnitTypeNames.Add(unitTypeName);
                }

                // Return index:
                return(index);
            }
            finally
            {
                // Release lock:
                baseUnitTypeLock.ReleaseLock();
            }
        }
        void IDisposable.Dispose()
        {
            ReaderWriterLock rwl = serverAccessLock;

            if (rwl == null)
            {
                return;
            }

            GC.SuppressFinalize(this);

            serverAccessLock = null;

            try
            {
                rwl.UpgradeToWriterLock(Timeout.Infinite);

                deadServers.ForEach(node => node.Dispose());
                workingServers.ForEach(node => node.Dispose());

                deadServers.Clear();
                workingServers.Clear();
                nodeLocator = null;

                isAliveTimer.Dispose();
                isAliveTimer = null;
            }
            finally
            {
                rwl.ReleaseLock();
            }
        }
Beispiel #16
0
        private static int GetBaseUnitIndex(string unitTypeName)
        {
            // Lock baseUnitTypeNames:
            baseUnitTypeLock.AcquireReaderLock(2000);

            try
            {
                // Retrieve index of unitTypeName:
                int index = baseUnitTypeNames.IndexOf(unitTypeName);

                // If not found, register unitTypeName:
                if (index == -1)
                {
                    baseUnitTypeLock.UpgradeToWriterLock(2000);
                    index = baseUnitTypeNames.Count;
                    baseUnitTypeNames.Add(unitTypeName);
                }

                // Return index:
                return(index);
            }
            finally
            {
                // Release lock:
                baseUnitTypeLock.ReleaseLock();
            }
        }
Beispiel #17
0
        void IDisposable.Dispose()
        {
            ReaderWriterLock rwl = this.serverAccessLock;

            if (rwl == null)
            {
                return;
            }

            GC.SuppressFinalize(this);

            this.serverAccessLock = null;

            try
            {
                rwl.UpgradeToWriterLock(Timeout.Infinite);

                this.deadServers.ForEach(delegate(MemcachedNode node) { node.Dispose(); });
                this.workingServers.ForEach(delegate(MemcachedNode node) { node.Dispose(); });

                this.deadServers.Clear();
                this.workingServers.Clear();
                this.nodeLocator = null;

                this.isAliveTimer.Dispose();
                this.isAliveTimer = null;
            }
            finally
            {
                rwl.ReleaseLock();
            }
        }
Beispiel #18
0
 public void transferencia(int cuentaOrigen, int cuentaDestino, double cantidad)
 {
     rwl.AcquireWriterLock(-1);
     try
     {
         if (cuentas[cuentaOrigen] < cantidad)//evalúa q el saldo no es inferior a la transferencia
         {
             Console.WriteLine("-------------------CANTIDAD INSUFICIENTE" + cuentaOrigen + "......SALDO: " + cuentas[cuentaOrigen] + "...." + cantidad);
             return;
         }
         else
         {
             Console.WriteLine("----------CANTIDAD OK----------" + cuentaOrigen);
         }
         Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
         cuentas[cuentaOrigen] -= cantidad;//dinero q sale de la cuenta origen
         Console.WriteLine(cantidad + " de " + cuentaOrigen + " para " + cuentaDestino);
         cuentas[cuentaDestino] += cantidad;
         Console.WriteLine("Saldo total: " + getSaldoTotal());
     }
     finally
     {
         rwl.ReleaseLock();
     }
 }
Beispiel #19
0
        TicksFile GetFile(int dt)
        {
            _lock.AcquireReaderLock(1000);
            try
            {
                if ((file_GetFileCache != null) && (file_GetFileCache.Include(dt)))
                {
                    return(file_GetFileCache);
                }

                foreach (TicksFile f in ticksFileList)
                {
                    if (f.Include(dt))
                    {
                        file_GetFileCache = f;
                        return(f);
                    }
                }

                LockCookie lc = _lock.UpgradeToWriterLock(1000);
                try
                {
                    DateTime startDate = new DateTime(DateTime2Int.DateTime(dt).Year, DateTime2Int.DateTime(dt).Month, 1);
                    DateTime endDate   = startDate.AddMonths(1).AddSeconds(-1);

                    string fileName = Path.Combine(dataDir, symbol + " " + startDate.ToString("yyyyMM") + TicksFile.FileExt);
                    //Создаю уникальное имя для файла, чтобы не затереть данные
                    int i = 1;
                    while (File.Exists(fileName))
                    {
                        l.Error("Не уникальное имя файла с тиками " + fileName);
                        fileName = Path.Combine(dataDir, symbol + " " + startDate.ToString("yyyyMM") + "[" + i + "]" + TicksFile.FileExt);
                        ++i;
                    }

                    TicksFile newTickFile = new TicksFile(
                        fileName,
                        symbol,
                        DateTime2Int.Int(startDate),
                        DateTime2Int.Int(endDate));

                    ticksFileList.Add(newTickFile);

                    staticLock.AcquireWriterLock(10000);
                    try { allTicksFileList.Add(newTickFile); }
                    finally { staticLock.ReleaseLock(); }

                    file_GetFileCache = newTickFile;
                    return(newTickFile);
                }
                finally
                {
                    _lock.DowngradeFromWriterLock(ref lc);
                }
            }
            finally
            {
                _lock.ReleaseReaderLock();
            }
        }
            public TestLockCookie ReleaseLock()
            {
                TestLockCookie tlc        = null;
                LockCookie     lockCookie = default(LockCookie);

                PerformLockAction(
                    0 /* expectedFailureHResult */,
                    false /* isBlockingOperation */,
                    () => lockCookie = _rwl.ReleaseLock(),
                    () =>
                {
                    tlc = new TestLockCookie()
                    {
                        _lockCookie  = lockCookie,
                        _readerLevel = ThreadReaderLevel,
                        _writerLevel = _writerLevel
                    };

                    if (_writerLevel != 0)
                    {
                        Assert.Equal(Environment.CurrentManagedThreadId, _writerThreadID);
                    }
                    ThreadReaderLevel = 0;
                    _writerLevel      = 0;
                    _writerThreadID   = InvalidThreadID;
                });
                return(tlc);
            }
Beispiel #21
0
 private List <Dictionary <int, List <CandleData> > > DequeueAllQuotes()
 {
     try
     {
         lockQueue.AcquireReaderLock(LockTimeout);
     }
     catch (ApplicationException)
     {
         return(null);
     }
     try
     {
         if (quoteQueue == null || quoteQueue.Count == 0)
         {
             return(null);
         }
         lockQueue.UpgradeToWriterLock(LockTimeout);
         var quotes = quoteQueue;
         quoteQueue = null;
         return(quotes);
     }
     finally
     {
         lockQueue.ReleaseLock();
     }
     return(null);
 }
Beispiel #22
0
        private void UpdateUnitState(string code, string status, string description)
        {
            unitsLocker.AcquireReaderLock(LockTimeout);
            try
            {
                // найти модуль
                var unit = units.Find(u => u.Code == code);
                if (unit == null)
                {
                    return;
                }
                var state = (ServiceProcessState)Enum.Parse(typeof(ServiceProcessState),
                                                            status, true);

                // получить доступ на запись
                unitsLocker.UpgradeToWriterLock(LockTimeout);
                unit.LastServiceState.AddError(state, description, DateTime.Now);
                unit.LastUpdated = DateTime.Now;
            }
            catch (Exception ex)
            {
                var stack = new StackTrace(ex, true);
                Logger.Error(string.Format("Error in UpdateUnitState(UDP), line {0}, col {1}",
                                           stack.GetFrame(0).GetFileLineNumber(), stack.GetFrame(0).GetFileColumnNumber()), ex);
                throw;
            }
            finally
            {
                unitsLocker.ReleaseLock();
            }
        }
        public Type ResolveType(string fullname)
        {
            _lock.AcquireReaderLock(Timeout.Infinite);

            try {
                if (_cache.ContainsKey(fullname))
                {
                    return(_cache[fullname]);
                }

                Type type = null;
                foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
                {
                    type = a.GetType(fullname, false, false);

                    if (type != null)
                    {
                        break;
                    }
                }

                _lock.UpgradeToWriterLock(Timeout.Infinite);

                _cache.Add(fullname, type);
                return(type);
            }
            finally {
                _lock.ReleaseLock();
            }
        }
        protected void CheckCacheExists()
        {
            // lock...
            _lock.AcquireReaderLock(-1);



            // do we have it?
            if (_cache == null)
            {
                // upgrade...
                _lock.UpgradeToWriterLock(-1);



                // create it...
                _cache = new Hashtable();
                foreach (EnterpriseCounter counter in InnerList)
                {
                    _cache.Add(counter.Name.ToLower(), counter);
                }
            }



            // unlock...
            _lock.ReleaseLock();
        }
Beispiel #25
0
        protected bool IsInternalToDynamicProxy(Assembly asm)
        {
#if dotNet2
            internalsToDynProxyLock.AcquireReaderLock(-1);
            try
            {
                if (!internalsToDynProxy.ContainsKey(asm))
                {
                    internalsToDynProxyLock.UpgradeToWriterLock(-1);
                    InternalsVisibleToAttribute[] atts = (InternalsVisibleToAttribute[])asm.GetCustomAttributes(typeof(InternalsVisibleToAttribute), false);
                    bool found = false;
                    foreach (InternalsVisibleToAttribute internals in atts)
                    {
                        if (internals.AssemblyName.Contains(ModuleScope.ASSEMBLY_NAME))
                        {
                            found = true;
                            break;
                        }
                    }
                    internalsToDynProxy.Add(asm, found);
                }
                return(internalsToDynProxy[asm]);
            }
            finally
            {
                internalsToDynProxyLock.ReleaseLock();
            }
#else
            return(false);
#endif
        }
Beispiel #26
0
        /// <summary>
        /// Get the specified TID and t. Returns false if it isn't found.
        /// </summary>
        /// <param name="TID">TI.</param>
        /// <param name="t">T.</param>
        public bool Get(UInt64 TID, out TunnelBase t)
        {
            lReadWriteLock.AcquireReaderLock(READER_LOCK_TIMEOUT_MS);
            bool ret = this.mTunnels.Find(ref TID, out t);

            lReadWriteLock.ReleaseLock();
            return(ret);
        }
Beispiel #27
0
    // Shows how to release all locks and later restore
    // the lock state. Shows how to use sequence numbers
    // to determine whether another thread has obtained
    // a writer lock since this thread last accessed the
    // resource.
    static void ReleaseRestore(int timeOut)
    {
        int lastWriter;

        try
        {
            rwl.AcquireReaderLock(timeOut);
            try
            {
                // It is safe for this thread to read from
                // the shared resource. Cache the value. (You
                // might do this if reading the resource is
                // an expensive operation.)
                int resourceValue = resource;
                Display("reads resource value " + resourceValue);
                Interlocked.Increment(ref reads);

                // Save the current writer sequence number.
                lastWriter = rwl.WriterSeqNum;

                // Release the lock, and save a cookie so the
                // lock can be restored later.
                LockCookie lc = rwl.ReleaseLock();

                // Wait for a random interval (up to a
                // quarter of a second), and then restore
                // the previous state of the lock. Note that
                // there is no time-out on the Restore method.
                Thread.Sleep(rnd.Next(250));
                rwl.RestoreLock(ref lc);

                // Check whether other threads obtained the
                // writer lock in the interval. If not, then
                // the cached value of the resource is still
                // valid.
                if (rwl.AnyWritersSince(lastWriter))
                {
                    resourceValue = resource;
                    Interlocked.Increment(ref reads);
                    Display("resource has changed " + resourceValue);
                }
                else
                {
                    Display("resource has not changed " + resourceValue);
                }
            }
            finally
            {
                // Ensure that the lock is released.
                rwl.ReleaseReaderLock();
            }
        }
        catch (ApplicationException)
        {
            // The reader lock request timed out.
            Interlocked.Increment(ref readerTimeouts);
        }
    }
Beispiel #28
0
 /// <inheritdoc />
 public void Dispose()
 {
     if (m_IsDisposed == true)
     {
         return;
     }
     m_IsDisposed.Value = true;
     Locker.ReleaseLock();
 }
 /// <summary>
 /// Releases unmanaged and - optionally - managed resources.
 /// </summary>
 /// <param name="alsoManaged"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
 private void Dispose(bool alsoManaged)
 {
     if (m_IsDisposed == true)
     {
         return;
     }
     m_IsDisposed.Value = true;
     Locker.ReleaseLock();
 }
Beispiel #30
0
        //To save data in human-readable format
        private static void Save(SpillData spill)
        {
            ReaderWriterLock locker = new ReaderWriterLock();

            try
            {
                locker.AcquireWriterLock(10000);//timeout of 10 seconds,
                using (sw = new StreamWriter(PP.myRun.OutFileName, true))
                {
                    try
                    {
                        sw.WriteLine("--Begin of spill (ascii)");
                        sw.WriteLine("--** Source = " + spill.Source);
                        sw.WriteLine("--SpillHeader");
                        sw.Write(spill.SpillWordCount + " "); //Word counts in spill
                        sw.Write(spill.SpillTrigCount + " "); //Number of triggers in spill
                        sw.Write(spill.SpillCounter + " ");   //Spill number
                        sw.Write(spill.ExpectNumCh + " ");    //Channel mask
                        sw.Write(spill.BoardID + " ");        //Board ID
                        sw.Write(spill.SpillStatus);          //Spill status
                        sw.WriteLine("--End SpillHeader");
                        sw.WriteLine("--Events");
                        foreach (Mu2e_Event spillEvent in spill.SpillEvents)
                        {
                            sw.WriteLine("--EventHeader");
                            sw.Write(spillEvent.EventWordCount + " "); //Word count in event
                            sw.Write(spillEvent.EventTimeStamp + " "); //Timestamp for event
                            sw.Write(spillEvent.TrigCounter + " ");    //Trigger number for event
                            sw.Write(spillEvent.NumSamples + " ");     //Number of ADC samples per event
                            sw.Write(spillEvent.TrigType + " ");       //Type of trigger
                            sw.Write(spillEvent.EventStatus);          //Event status
                            sw.WriteLine("--End EventHeader");

                            foreach (Mu2e_Ch chan in spillEvent.ChanData)
                            {
                                sw.Write(chan.num_ch + " "); //Write the channel number
                                foreach (int adc in chan.data)
                                {
                                    sw.Write(adc + " "); //Write the ADC data
                                }
                                sw.Write("\r\n");
                            }
                        }
                        sw.WriteLine("--End Events");
                        sw.WriteLine("--End of spill (ascii)");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Exception thrown in TCP_receiver::Save(SpillData spill) : " + e);
                    }
                }
            }
            finally
            {
                locker.ReleaseLock();
            }
        }