// Shows how to request and release a reader lock, and // how to handle time-outs. static void ReadFromResource(int timeOut) { try { rwl.AcquireReaderLock(timeOut); try { // It is safe for this thread to read from // the shared resource. Display("reads resource value " + resource); Interlocked.Increment(ref reads); } finally { // Ensure that the lock is released. rwl.ReleaseReaderLock(); } } catch (ApplicationException) { // The reader lock request timed out. Interlocked.Increment(ref readerTimeouts); } }
/// <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); }
public List <Track> LoadManifestFromFile() { var manifest = new List <Track>(); var manifestPath = DetermineManifestPath(); if (!File.Exists(manifestPath)) { return(manifest); } ReadWriteManifestLock.AcquireReaderLock(ReadLockTimeoutMs); try { using (var sr = new StreamReader(manifestPath)) { var jsonManifestText = sr.ReadToEnd(); manifest = JsonConvert.DeserializeObject <List <Track> >(jsonManifestText); } } finally { ReadWriteManifestLock.ReleaseReaderLock(); } return(manifest); }
public void TestBug_55909() { rwlock = new ReaderWriterLock(); ThreadRunner tr = StartThread(new ThreadStart(Bug_55909_Thread2)); Thread.Sleep(200); rwlock.AcquireReaderLock(Timeout.Infinite); try { LockCookie lc = rwlock.UpgradeToWriterLock(Timeout.Infinite); Thread.Sleep(500); } finally { rwlock.ReleaseReaderLock(); } tr.Join(); }
private static string GetBaseUnitName(int index) { // Lock baseUnitTypeNames: baseUnitTypeLock.AcquireReaderLock(2000); try { return(baseUnitTypeNames[index]); } finally { // Release lock: baseUnitTypeLock.ReleaseReaderLock(); } }
/// <summary> /// Gets or sets the element at the specified index. /// </summary> /// <returns> /// The element at the specified index. /// </returns> /// /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>. /// </exception> /// /// <exception cref="T:System.NotSupportedException"> /// The property is set and the <see cref="T:System.Collections.Generic.IList`1"/> is read-only. /// </exception> public T this[int index] { get { syncLock.AcquireReaderLock(Timeout.Infinite); T result = collection[index]; syncLock.ReleaseReaderLock(); return(result); } set { syncLock.AcquireWriterLock(Timeout.Infinite); if (collection.Count == 0 || collection.Count <= index) { syncLock.ReleaseWriterLock(); return; } collection[index] = value; syncLock.ReleaseWriterLock(); } }
public User GetUser(SessionId sessionId) { if (sessionId != null) { try { _Sync.AcquireReaderLock(Timeout.Infinite); UserItem ui; if (_AuthorizedUsers.TryGetValue(sessionId.Id, out ui)) { return(ui.User); } else { return(null); } } finally { _Sync.ReleaseReaderLock(); } } return(null); }
/* * This is called by the ASP.NET page */ public ClientNode getClientNode(PhysicalAddress p) { mutex.AcquireReaderLock(60000); foreach (ClientNode n in list) { if (n.mac == p) { return(n); } } mutex.ReleaseReaderLock(); return(null); }
public static DrawableScreen fetchOpaque(uint pid) { int timeout = 300; rwlock.AcquireReaderLock(timeout); try { foreach (DrawableScreen util in screens) { if (util.getPid() == pid) { if (util.Opacity == 1.00) { return(util); } } } return(null); } finally { rwlock.ReleaseReaderLock(); } }
/// <summary> /// Returns the type definition most appropiate for a value type. /// </summary> /// <param name="csharpType">type of a value</param> /// <returns>type definition</returns> public FudgeFieldType GetByCSharpType(Type csharpType) { if (csharpType == null) { return null; } rwLock.AcquireReaderLock(Timeout.Infinite); FudgeFieldType result = null; typesByCSharpType.TryGetValue(csharpType, out result); rwLock.ReleaseReaderLock(); return result; }
public int IndexOf(byte[] Search) { int IndexOf = -1; Lock.AcquireReaderLock(Timeout); try { int len = Length; if (len >= Search.Length) { for (int i = 0; i < len - Search.Length; i++) { int Found = 0; for (int j = 0; j < Search.Length - 1; j++) { int Pos = (ReadPos + i + j) % Buffer.Length; if (Buffer[Pos] == Search[j]) { Found += 1; } } if (Found == Search.Length) { IndexOf = i; break; } } } } finally { Lock.ReleaseReaderLock(); } return(IndexOf); }
public bool HaveSnapshotEvents <TE>(string symbol, string source) { rwl.AcquireReaderLock(lockTimeout); try { Dictionary <string, ReceivedSnapshot <TE> > dict = GetDictionary <TE>(); if (dict == null) { return(false); } bool isCompareSource = typeof(TE) == typeof(IDxOrder) && source != null && !source.Equals(string.Empty); foreach (ReceivedSnapshot <TE> snapshot in dict.Values) { if (!snapshot.Symbol.Equals(symbol)) { continue; } if (!isCompareSource) { return(snapshot.Events.Count > 0); } foreach (IDxOrder order in snapshot.Events) { if (order.Source.Equals(source)) { return(true); } } } } finally { rwl.ReleaseReaderLock(); } return(false); }
/// <summary> /// Return the xfer uploader for the given transaction. /// </summary> /// <remarks> /// If an uploader does not already exist for this transaction then it is created, otherwise the existing /// uploader is returned. /// </remarks> /// <param name="transactionID"></param> /// <returns>The asset xfer uploader</returns> public AssetXferUploader RequestXferUploader(UUID transactionID) { AssetXferUploader uploader; m_UploaderRwLock.AcquireReaderLock(-1); try { if (!XferUploaders.ContainsKey(transactionID)) { LockCookie lc = m_UploaderRwLock.UpgradeToWriterLock(-1); try { uploader = new AssetXferUploader(this, m_Scene, transactionID, m_dumpAssetsToFile); // m_log.DebugFormat( // "[AGENT ASSETS TRANSACTIONS]: Adding asset xfer uploader {0} since it didn't previously exist", transactionID); XferUploaders.Add(transactionID, uploader); } finally { m_UploaderRwLock.DowngradeFromWriterLock(ref lc); } } else { uploader = XferUploaders[transactionID]; } } finally { m_UploaderRwLock.ReleaseReaderLock(); } return(uploader); }
/// <summary> /// Use this method to write to stream directly from database /// </summary> /// <param name="data"></param> /// <returns></returns> public async Task WriteToStreamHistorical(TStreamItemCollection data) { _readerWriterLock.AcquireReaderLock(Timeout.Infinite); try { var items = _streamList.ToArray(); items = items .Where(x => !x.CancelationToken?.IsCancellationRequested ?? true) // No need to filter from DB //.Where(x => data.StreamItems.All(y => x.Filter.IsValid(y))) .ToArray(); foreach (var streamData in items) { await WriteToStream(data, streamData); } } finally { _readerWriterLock.ReleaseReaderLock(); } }
public string GetCachedStatement(string statementName) { string statement = null; syncLock.AcquireReaderLock(-1); try { if (statementDictionary.ContainsKey(statementName)) { statement = statementDictionary[statementName]; } } finally { syncLock.ReleaseReaderLock(); } if (statement == null) { syncLock.AcquireWriterLock(-1); try { if (statementDictionary.ContainsKey(statementName)) { statement = statementDictionary[statementName]; } else { Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream(statementName); using (StreamReader reader = new StreamReader(stream)) { statement = reader.ReadToEnd(); } statementDictionary[statementName] = statement; } } finally { syncLock.ReleaseWriterLock(); } } return(statement); }
/// <summary> /// Optimized with reader/writer lock. /// </summary> /// <param name="type"></param> /// <returns></returns> public ISessionFactory GetSessionFactory(Type type) { Type normalizedtype = GetRootType(type); if (normalizedtype == null) { throw new ActiveRecordException("No configuration for ActiveRecord found in the type hierarchy -> " + type.FullName); } readerWriterLock.AcquireReaderLock(-1); try { ISessionFactory sessFactory = type2SessFactory[normalizedtype] as ISessionFactory; if (sessFactory != null) { return(sessFactory); } LockCookie lc = readerWriterLock.UpgradeToWriterLock(-1); try { sessFactory = type2SessFactory[normalizedtype] as ISessionFactory; if (sessFactory != null) { return(sessFactory); } Configuration cfg = GetConfiguration(normalizedtype); sessFactory = cfg.BuildSessionFactory(); type2SessFactory[normalizedtype] = sessFactory; return(sessFactory); } finally { readerWriterLock.DowngradeFromWriterLock(ref lc); } } finally { readerWriterLock.ReleaseReaderLock(); } }
/// <summary> /// Returns the last written packet. /// </summary> /// <param name="channelId">Channel id.</param> /// <returns>Last written packet.</returns> public RtmpPacket GetLastWritePacket(int channelId) { try { ReaderWriterLock.AcquireReaderLock(); if (_writePackets.ContainsKey(channelId)) { return(_writePackets[channelId] as RtmpPacket); } } finally { ReaderWriterLock.ReleaseReaderLock(); } return(null); }
/// <summary> /// Returns the last read header for channel. /// </summary> /// <param name="channelId">Channel id.</param> /// <returns>Last read header.</returns> public RtmpHeader GetLastReadHeader(int channelId) { try { ReaderWriterLock.AcquireReaderLock(); if (_readHeaders.ContainsKey(channelId)) { return(_readHeaders[channelId] as RtmpHeader); } } finally { ReaderWriterLock.ReleaseReaderLock(); } return(null); }
public bool TryGetValue(TKey Key, out TValue Value) { // Does not modify the collection, use a reader lock AccessLock.AcquireReaderLock(Timeout.Infinite); bool ReturnValue = false; try { ReturnValue = ProtectedDictionary.TryGetValue(Key, out Value); } finally { AccessLock.ReleaseReaderLock(); } return(ReturnValue); }
static void Reader(object n) { rwl.AcquireReaderLock(time_ms); int v = data[0]; for (int i = 0; i < data.Length; ++i) { if (v != data[i]) { Console.WriteLine("ERROR: data are inconsistent: the first value is " + v + " incorrect value is" + data[i]); break; } } rwl.ReleaseReaderLock(); Interlocked.Decrement(ref wait); }
public static IEnumerable <string> ReadFile(string fileName) { try { rwl.AcquireReaderLock(100); return(File.ReadLines(fileName)); } catch { return(null); } finally { rwl.ReleaseReaderLock(); } }
public void Dispose() { if (Lock == null) { return; } if (Lock.IsWriterLockHeld) { Lock.ReleaseWriterLock(); } else if (Lock.IsReaderLockHeld) { Lock.ReleaseReaderLock(); } }
internal bool TryGet(Topic topic, out List <IDisposable> outValue) { _lock.AcquireReaderLock(_writerReaderTimeout); var result = false; outValue = null; if (_innerCollection.ContainsKey(topic)) { outValue = _innerCollection[topic].ToList(); result = true; } _lock.ReleaseReaderLock(); return(result); }
public string GetVirtualPath(string cacheKey) { try { _rwLock.AcquireReaderLock(Timeout.Infinite); if (_cache.ContainsKey(cacheKey)) { return(_cache[cacheKey]); } } finally { _rwLock.ReleaseReaderLock(); } return(null); }
public static string ReadAllText(string path) { string text = string.Empty; try { locker.AcquireReaderLock(int.MaxValue); text = File.ReadAllText(path); } finally { locker.ReleaseReaderLock(); } return(text); }
public static ProcessInformationList RetrieveProcessInformation(string projectName) { try { readWriterLock.AcquireReaderLock(100); if (DateTime.Now.Subtract(ManagedProcessInformationListCache[projectName].Age) >= new TimeSpan(0, 0, 10)) { UpdateCache(projectName); } return(ManagedProcessInformationListCache[projectName].ProcessInformationList); } finally { readWriterLock.ReleaseReaderLock(); } }
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(); } }
private MessageTemplate GetTemplate(string code) { MessageTemplate template; _lock.AcquireReaderLock(_timeout); try { template = Templates[code]; } finally { _lock.ReleaseReaderLock(); } return(template); }
public void Dispose() { if (rwlock == null) { return; } if (write) { rwlock.ReleaseWriterLock(); } else { rwlock.ReleaseReaderLock(); } rwlock = null; }
/// <summary> /// Look for the appender named as <c>name</c> /// </summary> /// <param name="name">The name of the appender to lookup</param> /// <returns>The appender with the name specified, or <c>null</c>.</returns> /// <remarks> /// <para> /// Returns the named appender, or null if the appender is not found. /// </para> /// </remarks> public virtual IAppender GetAppender(string name) { m_appenderLock.AcquireReaderLock(); try { if (m_appenderAttachedImpl == null || name == null) { return(null); } return(m_appenderAttachedImpl.GetAppender(name)); } finally { m_appenderLock.ReleaseReaderLock(); } }