/// <summary>
            /// Acquires the writer lock.
            /// </summary>
            /// <param name="timeoutMilliseconds">The timeout milliseconds.</param>
            /// <param name="releaser">The releaser.</param>
            /// <returns>Success</returns>
            private bool AcquireWriterLock(int timeoutMilliseconds, out IDisposable releaser)
            {
                releaser = SyncLockReleaser.Empty;

                if (Locker?.IsReaderLockHeld ?? false)
                {
                    Locker?.AcquireReaderLock(timeoutMilliseconds);
                    releaser = new SyncLockReleaser(this, LockHolderType.Read);
                    return(Locker?.IsReaderLockHeld ?? false);
                }

                Locker?.AcquireWriterLock(timeoutMilliseconds);
                if (Locker?.IsWriterLockHeld ?? false)
                {
                    releaser = new SyncLockReleaser(this, LockHolderType.Write);
                }

                return(Locker?.IsWriterLockHeld ?? false);
            }
        internal AdapterTransaction GetTransactionById(string transactionId)
        {
            AdapterTransaction transaction = null;

            syncLock.AcquireReaderLock(MessageEngine.Instance.LockMillisecondsTimeout);

            try
            {
                transactionDictionary.TryGetValue(transactionId, out transaction);
            }
            finally
            {
                syncLock.ReleaseReaderLock();
            }

            return(transaction);
        }
Esempio n. 3
0
 private Bitmap getFrame(int pos)
 {
     readerWriterLock.AcquireReaderLock(Timeout.Infinite);
     try
     {
         IVideoReader reader = VideoReader;
         if (reader == null)
         {
             return(null);
         }
         return(reader.ReadFrameBitmap(pos));
     }
     finally
     {
         readerWriterLock.ReleaseReaderLock();
     }
 }
Esempio n. 4
0
        private IEnumerable <TypeDef> GetTypeDefs()
        {
            //lock (TypeDefCacheLock)
            TypeDefCacheLock.AcquireReaderLock(LockTimeout);
            try
            {
                if (TypeDefCache != null)
                {
                    return(TypeDefCache);
                }

                var lc = TypeDefCacheLock.UpgradeToWriterLock(LockTimeout);
                try
                {
                    if (TypeDefCache != null)
                    {
                        return(TypeDefCache);                      // Убедиться, что другой процесс уже не создал список
                    }
                    TypeDefCache = new List <TypeDef>();

                    using (var command = DataContext.CreateCommand(SelectDataTypeSql))
                    {
                        using (var reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                TypeDefCache.Add(new TypeDef
                                {
                                    Id   = reader.GetInt16(0),
                                    Name = reader.IsDBNull(1) ? String.Empty : reader.GetString(1)
                                });
                            }
                        }
                    }
                    return(TypeDefCache);
                }
                finally
                {
                    TypeDefCacheLock.DowngradeFromWriterLock(ref lc);
                }
            }
            finally
            {
                TypeDefCacheLock.ReleaseReaderLock();
            }
        }
Esempio n. 5
0
        public static ScriptInstance Load(ObjectPart part, ObjectPartInventoryItem item, UGUI user, AssetData data, CultureInfo currentCulture, byte[] serializedState = null, Func <string, TextReader> openInclude = null)
        {
            return(m_CompilerLock.AcquireReaderLock(() =>
            {
                IScriptAssembly assembly = m_LoadedAssemblies.GetOrAddIfNotExists(data.ID, () =>
                {
                    using (var reader = new StreamReader(data.InputStream))
                    {
                        return CompilerRegistry.ScriptCompilers.Compile(AppDomain.CurrentDomain, user, data.ID, reader, currentCulture, openInclude);
                    }
                });

                ScriptInstance instance = assembly.Instantiate(part, item, serializedState);
                m_LoadedInstances.GetOrAddIfNotExists(data.ID, () => new RwLockedList <ScriptInstance>()).Add(instance);
                return instance;
            }));
        }
Esempio n. 6
0
 static void ThreadReader()
 {
     for (int i = 0; i < 3; i++)
     {
         try
         {
             // AcquireReaderLock() raises an
             // ApplicationException when timed out.
             rwl.AcquireReaderLock(1000);
             Console.WriteLine("Begin Read  theResource = {0}", theResource);
             Thread.Sleep(10);
             Console.WriteLine("End   Read  theResource = {0}", theResource);
             rwl.ReleaseReaderLock();
         }
         catch (ApplicationException) { Console.WriteLine("reader error"); /* ... */ }
     }
 }
Esempio n. 7
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="properties"></param>
 /// <returns></returns>
 public Type GetDynamicClass(IEnumerable <DynamicProperty> properties)
 {
     rwLock.AcquireReaderLock(Timeout.Infinite);
     try {
         Signature signature = new Signature(properties);
         Type      type;
         if (!classes.TryGetValue(signature, out type))
         {
             type = CreateDynamicClass(signature.properties);
             classes.Add(signature, type);
         }
         return(type);
     }
     finally {
         rwLock.ReleaseReaderLock();
     }
 }
Esempio n. 8
0
        private MonitorData GetNodeData()
        {
            rwLock.AcquireReaderLock(LockTimeout);
            try
            {
                if (Node != null)
                {
                    return(Node.Data ?? (Node.Data = new MonitorData()));
                }

                return(null);
            }
            finally
            {
                rwLock.ReleaseReaderLock();
            }
        }
Esempio n. 9
0
 // Thread-safe
 internal VirtualKey Get(IntPtr hKey)
 {
     keysRwl.AcquireReaderLock(Timeout.Infinite);
     try
     {
         int handle = ToHandle(hKey);
         if (!keys_.ContainsKey(handle))
         {
             return(null);
         }
         return(keys_[handle]);
     }
     finally
     {
         keysRwl.ReleaseReaderLock();
     }
 }
Esempio n. 10
0
        /// <summary>
        /// Get a module commander
        /// </summary>
        /// <param name="name"></param>
        /// <returns>The module commander, null if no module commander with that name was found</returns>
        public ICommander GetCommander(string name)
        {
            m_moduleCommandersRwLock.AcquireReaderLock(-1);
            try
            {
                if (m_moduleCommanders.ContainsKey(name))
                {
                    return(m_moduleCommanders[name]);
                }
            }
            finally
            {
                m_moduleCommandersRwLock.ReleaseReaderLock();
            }

            return(null);
        }
Esempio n. 11
0
        //============================================================================
        // Server.getFileStream
        //============================================================================
        public static FileStream getFileStream(int index)
        {
            if (index == -1)
            {
                return(null);
            }

            mFileListRWLock.AcquireReaderLock(-1);
            try
            {
                return(mFileList[index] as FileStream);
            }
            finally
            {
                mFileListRWLock.ReleaseReaderLock();
            }
        }
Esempio n. 12
0
 private static void ReadLock(Action action)
 {
     if (rwLock.IsReaderLockHeld || rwLock.IsWriterLockHeld)
     {
         action();
         return;
     }
     rwLock.AcquireReaderLock(Timeout.Infinite);
     try
     {
         action();
     }
     finally
     {
         rwLock.ReleaseReaderLock();
     }
 }
Esempio n. 13
0
 /// <summary>
 /// 确定某元素是否在集合中
 /// </summary>
 /// <param name="item">要定位的对象. 对于引用类型, 该值可以为 null</param>
 public bool Contains(T item)
 {
     _rwLock.AcquireReaderLock(Timeout.Infinite);
     try
     {
         return(_infos.Contains(item));
     }
     finally
     {
         _rwLock.ReleaseReaderLock();
     }
 }
Esempio n. 14
0
 public static void ImportDatabase()
 {
     try
     {
         locker.AcquireReaderLock(Int32.MaxValue);
         using (var stream = new StreamReader(DatabasePath))
         {
             Json database = Json.Import(stream);
             Json cameras  = database["Cameras"];
             for (int i = 0; i < cameras.Count; i++)
             {
                 Json   cameraJson = cameras[i];
                 Camera camera     = new Camera(cameraJson["ID"], cameraJson["Name"]);
                 Repository <Camera> .Add(camera);
             }
             Json parkingLots = database["ParkingLots"];
             for (int i = 0; i < parkingLots.Count; i++)
             {
                 Json       lotJson    = parkingLots[i];
                 ParkingLot lot        = new ParkingLot(lotJson["ID"], lotJson["Name"], Repository <Camera> .Get(lotJson["Camera"]));
                 string     bitmapPath = $"{HttpRuntime.AppDomainAppPath}App_Data\\{(int)lotJson["ID"]}.jpg";
                 if (File.Exists(bitmapPath))
                 {
                     lot.Baseline = new Bitmap(Bitmap.FromFile(bitmapPath) as Bitmap);
                 }
                 for (int a = 0; a < lotJson["Annotations"].Count; a++)
                 {
                     Json       ann        = lotJson["Annotations"][a];
                     Annotation annotation = new Annotation(ann["ID"], (Annotation.AnnotationType)(int) ann["Type"]);
                     for (int p = 0; p < ann["Points"].Count; p++)
                     {
                         Json point = ann["Points"][p];
                         Models.Geometry.Vector2 pnt = new Models.Geometry.Vector2(point["X"], point["Y"]);
                         annotation.Add(pnt);
                     }
                     lot.Annotations.Add(annotation);
                 }
                 Repository <ParkingLot> .Add(lot);
             }
         }
     } finally
     {
         locker.ReleaseReaderLock();
     }
 }
Esempio n. 15
0
        /// <summary>
        /// Возвращает потомков для типа документа
        /// </summary>
        /// <param name="docDefId">Идентификатор типа документа</param>
        /// <returns>Список идентификаторов потомков</returns>
        //[SmartCache(TimeOutSeconds = 3600)]
        public IEnumerable <Guid> GetDocDefDescendant(Guid docDefId)
        {
            DocDefDescendantCacheLock.AcquireReaderLock(LockTimeout);
            try
            {
                var cache = DocDefDescendantCache.Find(docDefId);
                if (cache != null)
                {
                    return(cache.CachedObject);
                }

                var lc = DocDefDescendantCacheLock.UpgradeToWriterLock(LockTimeout);
                try
                {
                    cache = DocDefDescendantCache.Find(docDefId);
                    if (cache != null)
                    {
                        return(cache.CachedObject);
                    }

                    var docDefs = (
                        from docDef in DataContext.GetEntityDataContext().Entities.Object_Defs.OfType <Document_Def>()
                        where docDef.Ancestor_Id == docDefId
                        select docDef.Id).ToList();

                    foreach (var id in docDefs)
                    {
                        docDefs = new List <Guid>(docDefs.Union(GetDocDefDescendant(id)));
                    }

                    docDefs = new List <Guid>(docDefs.Union(new[] { docDefId }));
                    DocDefDescendantCache.Add(docDefs, docDefId);

                    return(docDefs);
                }
                finally
                {
                    DocDefDescendantCacheLock.DowngradeFromWriterLock(ref lc);
                }
            }
            finally
            {
                DocDefDescendantCacheLock.ReleaseReaderLock();
            }
        }
Esempio n. 16
0
        /// <summary>
        /// 读取文件缓存
        /// </summary>
        /// <param name="name"></param>
        /// <param name="last"></param>
        /// <returns></returns>
        public static object ReadCache(string name, DateTime last, string folder)
        {
            Stream stream = null;

            try
            {
                string path = CachePath;
                if (!string.IsNullOrEmpty(folder))
                {
                    path = Path.Combine(CachePath, folder);
                }
                name = Path.Combine(path, name + ".dat");
                var fi = new FileInfo(name);
                if (fi.LastWriteTime < last)
                {
                    return(null);
                }

                rwl.AcquireReaderLock(1000);//读锁,1秒后未获取放弃

                stream = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.Read);
                GZipStream compressionStream = new GZipStream(stream, CompressionMode.Decompress);
                var        obj = formatter.Deserialize(compressionStream);
                compressionStream.Close();
                compressionStream.Dispose();
                return(obj);
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("读取缓存" + name + "失败" + DateTime.Now.ToString() + ":" + ex.Message);
                return(null);
            }
            finally
            {
                if (rwl.IsReaderLockHeld)
                {
                    rwl.ReleaseReaderLock();
                }
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            }
        }
Esempio n. 17
0
        private void AcquireLock()
        {
            switch (_mode)
            {
            case LockMode.Read:
                _lock.AcquireReaderLock(_timeout);
                break;

            case LockMode.UpgrateToWrite:
                _cookie = _lock.UpgradeToWriterLock(_timeout);
                break;

            case LockMode.Write:
                _lock.AcquireWriterLock(_timeout);
                break;
            }
            Logger.TraceFormat("lock {0} acured", _mode);
        }
Esempio n. 18
0
        public const int CacheSerializationTimeout = 30000;         // Wait at most 30 seconds for a timestamp to be deserialized

        protected internal void AcquireCacheLock(IServerProcess process, LockMode mode)
        {
            try
            {
                if (mode == LockMode.Exclusive)
                {
                    _cacheLock.AcquireWriterLock(CacheLockTimeout);
                }
                else
                {
                    _cacheLock.AcquireReaderLock(CacheLockTimeout);
                }
            }
            catch
            {
                throw new ServerException(ServerException.Codes.CacheLockTimeout);
            }
        }
            public static void Acquire(out LiteLock liteLock, ReaderWriterLock locker, bool forWrite)
            {
                LiteLock theLock = new LiteLock(locker, forWrite);

                try { }
                finally
                {
                    if (forWrite)
                    {
                        locker.AcquireWriterLock(theLock.timeout);
                    }
                    else
                    {
                        locker.AcquireReaderLock(theLock.timeout);
                    }
                    liteLock = theLock;
                }
            }
Esempio n. 20
0
        /// <summary>
        /// Reads the content of the SharedVariable as an hexadecimal string representation
        /// </summary>
        /// <returns>the content of the SharedVariable in hexadecimal format as string</returns>
        public virtual string ReadStringData()
        {
#if SharedVarsStoredAsRawString
            return(Data);
#else
            StringBuilder sb;

            rwLock.AcquireReaderLock(-1);
            sb = new StringBuilder(data.Length * 2);
            for (int i = 0; i < data.Length; ++i)
            {
                sb.Append(data[i].ToString("X2"));
            }
            rwLock.ReleaseReaderLock();

            return(sb.ToString());
#endif
        }
Esempio n. 21
0
        public LockingObject(ReaderWriterLock rwLock, AccessMode lockMode)
        {
            _rwLock     = rwLock;
            _accessMode = lockMode;

            if (_accessMode == AccessMode.Read)
            {
                _rwLock.AcquireReaderLock(-1);
            }
            else if (_accessMode == AccessMode.Write)
            {
                _rwLock.AcquireWriterLock(-1);
            }
            else //UpAndDowngrade
            {
                _lockCookie = _rwLock.UpgradeToWriterLock(-1);
            }
        }
Esempio n. 22
0
        public IEnumerable <Celeb> GetAll()
        {
            String celebsJson = string.Empty;

            try
            {
                readerWriterLock.AcquireReaderLock(lockTimeout_in_ms);
                celebsJson = File.ReadAllText(celebs_json_path);
            }
            finally
            {
                readerWriterLock.ReleaseReaderLock();
            }

            var result = JsonConvert.DeserializeObject <IEnumerable <Celeb> >(celebsJson);

            return(result);
        }
Esempio n. 23
0
        public virtual AuthenticateResponse AuthenticateSession(UUID sessionID, UUID agentID, uint circuitcode)
        {
            AgentCircuitData validcircuit = null;

            m_AgentCircuitsLock.AcquireReaderLock(-1);
            try
            {
                if (m_agentCircuits.ContainsKey(circuitcode))
                {
                    validcircuit = m_agentCircuits[circuitcode];
                }
            }
            finally
            {
                m_AgentCircuitsLock.ReleaseReaderLock();
            }

            AuthenticateResponse user = new AuthenticateResponse();

            if (validcircuit == null)
            {
                //don't have this circuit code in our list
                user.Authorised = false;
                return(user);
            }

            if ((sessionID == validcircuit.SessionID) && (agentID == validcircuit.AgentID))
            {
                user.Authorised                = true;
                user.LoginInfo                 = new Login();
                user.LoginInfo.Agent           = agentID;
                user.LoginInfo.Session         = sessionID;
                user.LoginInfo.SecureSession   = validcircuit.SecureSessionID;
                user.LoginInfo.First           = validcircuit.firstname;
                user.LoginInfo.Last            = validcircuit.lastname;
                user.LoginInfo.InventoryFolder = validcircuit.InventoryFolder;
                user.LoginInfo.BaseFolder      = validcircuit.BaseFolder;
                user.LoginInfo.StartPos        = validcircuit.startpos;
            }
            else
            {
                // Invalid
                user.Authorised = false;
            }

            return(user);
        }
Esempio n. 24
0
 public static void GetLocation(out long x, out long y)
 {
     try
     {
         rwLock.AcquireReaderLock(1000);
         x = MapData.x;
         y = MapData.y;
     }
     catch (Exception)
     {
         x = 0;
         y = 0;
     }
     finally
     {
         rwLock.ReleaseReaderLock();
     }
 }
Esempio n. 25
0
 private static void buildLocalData()
 {
     try
     {
         readerWriterLock.AcquireReaderLock(int.MaxValue);
         _ips = JsonConvert.DeserializeObject <List <Ip> >(File.ReadAllText(_jsonFilePath));
     }
     catch (Exception e)
     {
         Console.WriteLine($"The file {_jsonFilePath} could not be deserialized: ");
         Console.WriteLine(e.Message);
         _ips = new List <Ip>();
     }
     finally
     {
         readerWriterLock.ReleaseReaderLock();
     }
 }
Esempio n. 26
0
 public static void ReaderLock(Action action, ReaderWriterLock rwl)
 {
     try
     {
         rwl.AcquireReaderLock(int.MaxValue);
         try
         {
             action();
         }
         finally
         {
             rwl.ReleaseReaderLock();
         }
     }
     catch (ApplicationException)
     {
     }
 }
Esempio n. 27
0
        public static ResultType GetReadLock <ResultType>(ReaderWriterLock lockObj, int timeout, DoWorkFunc <ResultType> doWork)
        {
            bool releaseLock = false;

            if (!lockObj.IsWriterLockHeld && !lockObj.IsReaderLockHeld)
            {
                lockObj.AcquireReaderLock(timeout);
                releaseLock = true;
            }
            try {
                return(doWork());
            } finally {
                if (releaseLock)
                {
                    lockObj.ReleaseReaderLock();
                }
            }
        }
Esempio n. 28
0
        public static String getOne()
        {
            readSemaphore.WaitOne();
            rwLock.AcquireReaderLock(Timeout.Infinite);
            String temp;

            try
            {
                temp = cells[0].ToString();
                cells.Remove(temp);
                s.Release();
            }
            finally
            {
                rwLock.ReleaseReaderLock();
            }
            return(temp);
        }
        protected virtual RouteFactory GetRouteFactory(string type)
        {
            _lock.AcquireReaderLock(Timeout.Infinite);
            try
            {
                RouteFactory factory;
                if (!_factories.TryGetValue(type, out factory))
                {
                    factory = _defaultFactory;
                }

                return(factory ?? _defaultFactory);
            }
            finally
            {
                _lock.ReleaseReaderLock();
            }
        }
Esempio n. 30
0
        /// <summary>
        /// Return all elements of the queue as an array.
        /// </summary>
        /// <returns>An array of all elements in the queue.</returns>
        public TValue[] ToArray()
        {
            // Does not modify the collection, use a reader lock
            AccessLock.AcquireReaderLock(Timeout.Infinite);
            TValue[] ReturnValues;

            try
            {
                ReturnValues = ProtectedQueue.ToArray();
            }

            finally
            {
                AccessLock.ReleaseReaderLock();
            }

            return(ReturnValues);
        }
Esempio n. 31
0
    public AutoLock(ReaderWriterLock l, bool forWrite)
    {
        this.l = l;

        if (this.forWrite = forWrite)
            l.AcquireWriterLock(timeout);
        else
            l.AcquireReaderLock(timeout);
    }
Esempio n. 32
0
        public static void InvalidTimeoutTest_ChangedInDotNetCore()
        {
            var rwl = new ReaderWriterLock();
            Assert.Throws<ArgumentOutOfRangeException>(() => rwl.AcquireReaderLock(-2));
            Assert.Throws<ArgumentOutOfRangeException>(() => rwl.AcquireReaderLock(TimeSpan.FromMilliseconds(-2)));
            Assert.Throws<ArgumentOutOfRangeException>(
                () => rwl.AcquireReaderLock(TimeSpan.FromMilliseconds((uint)int.MaxValue + 1)));

            Assert.Throws<ArgumentOutOfRangeException>(() => rwl.AcquireWriterLock(-2));
            Assert.Throws<ArgumentOutOfRangeException>(() => rwl.AcquireWriterLock(TimeSpan.FromMilliseconds(-2)));
            Assert.Throws<ArgumentOutOfRangeException>(
                () => rwl.AcquireWriterLock(TimeSpan.FromMilliseconds((uint)int.MaxValue + 1)));

            Assert.Throws<ArgumentOutOfRangeException>(() => rwl.UpgradeToWriterLock(-2));
            Assert.Throws<ArgumentOutOfRangeException>(() => rwl.UpgradeToWriterLock(TimeSpan.FromMilliseconds(-2)));
            Assert.Throws<ArgumentOutOfRangeException>(
                () => rwl.UpgradeToWriterLock(TimeSpan.FromMilliseconds((uint)int.MaxValue + 1)));
        }