/// <summary> /// Implements IOutboundTransport.UnsubscribeClient /// </summary> public void UnsubscribeClient(string clientId) { _listlock.AcquireReaderLock(DEFAULT_JOIN_TIMEOUT); try { if (!_clients.ContainsKey(clientId)) { throw new ClientNotSubscribedException(); } LockCookie ck = _listlock.UpgradeToWriterLock(DEFAULT_JOIN_TIMEOUT); try { UdpClientExpire client = _clients[clientId]; _clients.Remove(clientId); client.Client.Close(); } catch (Exception ex) { throw new TransportException("Unable to unsubscribe client", ex); } finally { _listlock.DowngradeFromWriterLock(ref ck); } } finally { _listlock.ReleaseReaderLock(); } }
/// <summary> /// 一次将对象添加到结尾处(如果已含则不添加) /// </summary> /// <param name="item">要添加的对象. 对于引用类型, 该值可以为 null</param> public bool AddOnce(T item) { _rwLock.AcquireReaderLock(Timeout.Infinite); try { if (!_infos.Contains(item)) { LockCookie lockCookie = _rwLock.UpgradeToWriterLock(Timeout.Infinite); try { DoAdd(item); return(true); } finally { _rwLock.DowngradeFromWriterLock(ref lockCookie); } } return(false); } finally { _rwLock.ReleaseReaderLock(); } }
Type CreateDynamicClass(DynamicProperty[] properties) { LockCookie cookie = rwLock.UpgradeToWriterLock(Timeout.Infinite); try { string typeName = "DynamicClass" + (classCount + 1); #if ENABLE_LINQ_PARTIAL_TRUST new ReflectionPermission(PermissionState.Unrestricted).Assert(); #endif try { TypeBuilder tb = this.module.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public, typeof(DynamicClass)); FieldInfo[] fields = GenerateProperties(tb, properties); GenerateEquals(tb, fields); GenerateGetHashCode(tb, fields); Type result = tb.CreateType(); classCount++; return(result); } finally { #if ENABLE_LINQ_PARTIAL_TRUST PermissionSet.RevertAssert(); #endif } } finally { rwLock.DowngradeFromWriterLock(ref cookie); } }
Type CreateDynamicClass(DynamicProperty[] properties) { LockCookie cookie = rwLock.UpgradeToWriterLock(Timeout.Infinite); try { string typeName = "DynamicClass" + (classCount + 1); try { TypeBuilder tb = this.module.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public, typeof(DynamicClass)); FieldInfo[] fields = GenerateProperties(tb, properties); GenerateEquals(tb, fields); GenerateGetHashCode(tb, fields); Type result = tb.CreateType(); classCount++; return(result); } finally { } } finally { rwLock.DowngradeFromWriterLock(ref cookie); } }
/// <summary> /// 将集合的元素复制到新数组中 /// <param name="clearSource">并清空源</param> /// </summary> public T[] ToArray(bool clearSource = false) { _rwLock.AcquireReaderLock(Timeout.Infinite); try { T[] result = _infos.ToArray(); if (clearSource) { LockCookie lockCookie = _rwLock.UpgradeToWriterLock(Timeout.Infinite); try { DoClear(); } finally { _rwLock.DowngradeFromWriterLock(ref lockCookie); } } return(result); } finally { _rwLock.ReleaseReaderLock(); } }
private bool IsValidValue(TKey key, TValue value) { if (IsCached) { if (key != null && value == null) { if (!_infos.TryGetValue(key, out value)) { return(false); } } if (((ICachedObject)value).IsInvalid) { if (key != null) { LockCookie lockCookie = _rwLock.UpgradeToWriterLock(Timeout.Infinite); try { _infos.Remove(key); } finally { _rwLock.DowngradeFromWriterLock(ref lockCookie); } } return(false); } } return(true); }
private void TrimValidValue() { if (IsCached) { List <TKey> invalids = new List <TKey>(); foreach (KeyValuePair <TKey, TValue> kvp in _infos) { if (((ICachedObject)kvp.Value).IsInvalid) { invalids.Add(kvp.Key); } } if (invalids.Count > 0) { LockCookie lockCookie = _rwLock.UpgradeToWriterLock(Timeout.Infinite); try { foreach (TKey item in invalids) { _infos.Remove(item); } } finally { _rwLock.DowngradeFromWriterLock(ref lockCookie); } } } }
public Bitmap GetBitmap(IconSize size, string fileName, bool isDirectory, bool forceLoad) { Bitmap retVal = null; sysImgListLock.AcquireReaderLock(1000); try { if (!sysImgList.IsImageListInited || size != sysImgList.CurrentImageListSize) { LockCookie lockCookie = sysImgListLock.UpgradeToWriterLock(Timeout.Infinite); try { SystemImageList imgList = sysImgList[size]; retVal = imgList[fileName, isDirectory, forceLoad]; } finally { sysImgListLock.DowngradeFromWriterLock(ref lockCookie); } } else { retVal = sysImgList[size][fileName, isDirectory, forceLoad]; } } finally { sysImgListLock.ReleaseReaderLock(); } return(retVal); }
/** * <summary> * Close all idle connections more then "timeout" milliseconds.</summary> * * <param name="timeout">Idle timeout in ms.</param> */ public void closeIdle(TimeSpan timeout) { LockCookie cookie = default(LockCookie); if (guard.IsReaderLockHeld) { cookie = guard.UpgradeToWriterLock(Timeout.Infinite); } else { guard.AcquireWriterLock(Timeout.Infinite); } try { removeConnections(conn => conn.CloseIfIdle(timeout)); } finally { if (cookie == default(LockCookie)) { guard.ReleaseWriterLock(); } else { guard.DowngradeFromWriterLock(ref cookie); } } }
/// <summary> /// Runs operation with Writer lock privelege. /// </summary> /// <param name="lockObj"></param> /// <param name="timeout"></param> /// <param name="doWork"></param> /// <returns></returns> public static void GetWriteLock(ReaderWriterLock lockObj, int timeout, DoWorkFunc doWork) { RWLockStatus status = (lockObj.IsWriterLockHeld ? RWLockStatus.WRITE_LOCK : (lockObj.IsReaderLockHeld ? RWLockStatus.READ_LOCK : RWLockStatus.UNLOCKED)); LockCookie writeLock = default(LockCookie); if (status == RWLockStatus.READ_LOCK) { writeLock = lockObj.UpgradeToWriterLock(timeout); } else if (status == RWLockStatus.UNLOCKED) { lockObj.AcquireWriterLock(timeout); } try { doWork(); } finally { if (status == RWLockStatus.READ_LOCK) { lockObj.DowngradeFromWriterLock(ref writeLock); } else if (status == RWLockStatus.UNLOCKED) { lockObj.ReleaseWriterLock(); } } }
// Shows how to request a reader lock, upgrade the // reader lock to the writer lock, and downgrade to a // reader lock again. static void UpgradeDowngrade(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); // If it is necessary to write to the resource, // you must either release the reader lock and // then request the writer lock, or upgrade the // reader lock. Note that upgrading the reader lock // puts the thread in the write queue, behind any // other threads that might be waiting for the // writer lock. try { LockCookie lc = rwl.UpgradeToWriterLock(timeOut); try { // It is safe for this thread to read or write // from the shared resource. resource = rnd.Next(500); Display("writes resource value " + resource); Interlocked.Increment(ref writes); } finally { // Ensure that the lock is released. rwl.DowngradeFromWriterLock(ref lc); } } catch (ApplicationException) { // The upgrade request timed out. Interlocked.Increment(ref writerTimeouts); } // When the lock has been downgraded, it is // still safe to read from the 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); } }
private static void AddHandler(object obj, RoadEvent e, RoadEventHandler del, bool unique) { if (obj == null) { throw new ArgumentNullException("obj", "No object given!"); } if (e == null) { throw new ArgumentNullException("e", "No event type given!"); } if (del == null) { throw new ArgumentNullException("del", "No event handler given!"); } if (!e.IsValidFor(obj)) { throw new ArgumentException("Object is not valid for this event type", "obj"); } try { GameEventMgr.m_lock.AcquireReaderLock(3000); try { RoadEventHandlerCollection roadEventHandlerCollection = (RoadEventHandlerCollection)GameEventMgr.m_GameObjectEventCollections[obj]; if (roadEventHandlerCollection == null) { roadEventHandlerCollection = new RoadEventHandlerCollection(); LockCookie lockCookie = GameEventMgr.m_lock.UpgradeToWriterLock(3000); try { GameEventMgr.m_GameObjectEventCollections[obj] = roadEventHandlerCollection; } finally { GameEventMgr.m_lock.DowngradeFromWriterLock(ref lockCookie); } } if (unique) { roadEventHandlerCollection.AddHandlerUnique(e, del); } else { roadEventHandlerCollection.AddHandler(e, del); } } finally { GameEventMgr.m_lock.ReleaseReaderLock(); } } catch (ApplicationException exception) { if (GameEventMgr.log.IsErrorEnabled) { GameEventMgr.log.Error("Failed to add local event handler!", exception); } } }
public bool Equals(LockCookie obj) { return _flags == obj._flags && _readerLevel == obj._readerLevel && _writerLevel == obj._writerLevel && _threadID == obj._threadID; }
public bool Equals(LockCookie obj) { return (_flags == obj._flags && _readerLevel == obj._readerLevel && _writerLevel == obj._writerLevel && _threadID == obj._threadID); }
// Token: 0x06000B7A RID: 2938 RVA: 0x0004A418 File Offset: 0x00048618 private static bool InternalCheckForAutomaticBooking(bool isEventForConfigObject, MailboxSession itemStore, CachedState cachedState) { cachedState.LockForRead(); CalendarConfiguration calendarConfiguration; try { calendarConfiguration = (cachedState.State[0] as CalendarConfiguration); if (calendarConfiguration == null || isEventForConfigObject) { LockCookie lockCookie = cachedState.UpgradeToWriterLock(); try { using (CalendarConfigurationDataProvider calendarConfigurationDataProvider = new CalendarConfigurationDataProvider(itemStore)) { calendarConfiguration = (CalendarConfiguration)calendarConfigurationDataProvider.Read <CalendarConfiguration>(null); if (calendarConfiguration == null) { Globals.Logger.LogEvent(InfoWorkerEventLogConstants.Tuple_CorruptCalendarConfiguration, null, new object[] { itemStore.MailboxOwner.LegacyDn }); calendarConfigurationDataProvider.Delete(new CalendarConfiguration()); calendarConfiguration = new CalendarConfiguration(); } } if (calendarConfiguration.AutomateProcessing == CalendarProcessingFlags.AutoAccept) { calendarConfiguration.AddNewRequestsTentatively = true; } cachedState.State[0] = calendarConfiguration; ResourceCheck.Tracer.TraceDebug((long)itemStore.GetHashCode(), "{0}: The calendar settings object was new or has been changed - (re)reading contents.", new object[] { TraceContext.Get() }); } catch (ObjectNotFoundException innerException) { ResourceCheck.Tracer.TraceError((long)itemStore.GetHashCode(), "{0}: The calendar configuration was deleted while we were looking at it. Back off and retry.", new object[] { TraceContext.Get() }); throw new TransientMailboxException(innerException); } finally { cachedState.DowngradeFromWriterLock(ref lockCookie); } } } finally { cachedState.ReleaseReaderLock(); } ResourceCheck.Tracer.TraceDebug <object, CalendarProcessingFlags>((long)itemStore.GetHashCode(), "{0}: MailboxType {1}", TraceContext.Get(), calendarConfiguration.AutomateProcessing); ResourceCheck.TracerPfd.TracePfd <int, object, CalendarProcessingFlags>((long)itemStore.GetHashCode(), "PFD IWR {0} {1}: ResourceMailbox: {2}", 19223, TraceContext.Get(), calendarConfiguration.AutomateProcessing); return(calendarConfiguration.AutomateProcessing == CalendarProcessingFlags.AutoAccept); }
// 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); } }
/// <summary> /// Get Wcf client instance. /// </summary> /// <typeparam name="TTypeBuilder">The proxy class builder.</typeparam> /// <param name="caching">Caching dictionary to use.</param> /// <param name="endpointConfigurationName">The name of the endpoint in the application configuration file.</param> /// <param name="remoteUri">The URI that identifies the service endpoint.</param> /// <param name="fromCaching">Whether get instance from caching or not.</param> /// <returns>Instance of a ClientBase derived class.</returns> private static TChannel GetInstance <TTypeBuilder>(Dictionary <string, TChannel> caching, string endpointConfigurationName, string remoteUri, bool fromCaching = true) where TTypeBuilder : IWcfClientTypeBuilder, new() { if (fromCaching) { string key = string.Format(WcfClientProxyDictionaryKeyStringFormat, endpointConfigurationName ?? string.Empty, string.IsNullOrEmpty(remoteUri) ? string.Empty : remoteUri.ToLowerInvariant()); Lock.AcquireReaderLock(Timeout.Infinite); try { if (caching.ContainsKey(key)) { return(caching[key]); } else { LockCookie lockCookie = Lock.UpgradeToWriterLock(Timeout.Infinite); try { if (caching.ContainsKey(key)) { return(caching[key]); } else { Type type = WcfClientType.BuildType <TChannel, TTypeBuilder>(); TChannel result = string.IsNullOrEmpty(remoteUri) ? (TChannel)Activator.CreateInstance(type, endpointConfigurationName) : (TChannel)Activator.CreateInstance(type, endpointConfigurationName, new EndpointAddress(remoteUri)); caching.Add(key, result); return(result); } } finally { Lock.DowngradeFromWriterLock(ref lockCookie); } } } finally { Lock.ReleaseReaderLock(); } } else { Type type = WcfClientType.BuildType <TChannel, TTypeBuilder>(); return(string.IsNullOrEmpty(remoteUri) ? (TChannel)Activator.CreateInstance(type, endpointConfigurationName) : (TChannel)Activator.CreateInstance(type, endpointConfigurationName, new EndpointAddress(remoteUri))); } }
private static void doWork(object objState) { List <KeyValuePair <string, ScheduledTasks.jobItem> > list = null; try { ScheduledTasks._RWLockDict.AcquireReaderLock(-1); ulong tickCount = Utilities.GetTickCount(); foreach (KeyValuePair <string, ScheduledTasks.jobItem> current in ScheduledTasks._dictSchedule) { if (tickCount > current.Value._ulRunAfter) { current.Value._ulRunAfter = 18446744073709551615uL; if (list == null) { list = new List <KeyValuePair <string, ScheduledTasks.jobItem> >(); } list.Add(current); } } if (list == null) { return; } LockCookie lockCookie = ScheduledTasks._RWLockDict.UpgradeToWriterLock(-1); try { foreach (KeyValuePair <string, ScheduledTasks.jobItem> current2 in list) { ScheduledTasks._dictSchedule.Remove(current2.Key); } if (ScheduledTasks._dictSchedule.Count < 1 && ScheduledTasks._timerInternal != null) { ScheduledTasks._timerInternal.Dispose(); ScheduledTasks._timerInternal = null; } } finally { ScheduledTasks._RWLockDict.DowngradeFromWriterLock(ref lockCookie); } } finally { ScheduledTasks._RWLockDict.ReleaseReaderLock(); } foreach (KeyValuePair <string, ScheduledTasks.jobItem> current3 in list) { try { current3.Value._oJob(); } catch (Exception) { } } }
public bool Load() { try { LockCookie upgrade = new LockCookie(); bool upgraded = false; if (locker.IsReaderLockHeld) { upgrade = locker.UpgradeToWriterLock(new TimeSpan(0, 1, 0)); upgraded = true; } else { locker.AcquireWriterLock(new TimeSpan(0, 1, 0)); } try { try { if (File.Exists(ConfigurationManagement.Instance.ConfigurationPath + Path.DirectorySeparatorChar + "IPLists.cfg")) { XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary <string, IPList>)); TextReader reader = new StreamReader(ConfigurationManagement.Instance.ConfigurationPath + Path.DirectorySeparatorChar + "IPLists.cfg"); iplists = (SerializableDictionary <string, IPList>)serializer.Deserialize(reader); reader.Close(); reader.Dispose(); } else { iplists = new SerializableDictionary <string, IPList>(); } } catch (Exception e) { Logging.LogCenter.Instance.LogException(e); iplists = new SerializableDictionary <string, IPList>(); } } finally { if (upgraded) { locker.DowngradeFromWriterLock(ref upgrade); } else { locker.ReleaseWriterLock(); } } return(true); } catch (ApplicationException ex) { Logging.LogCenter.Instance.LogException(ex); return(false); } }
void Bug_55909_bis_ReaderWriter() { rwlock.AcquireReaderLock(-1); LockCookie lc = rwlock.UpgradeToWriterLock(-1); Thread.Sleep(1000); rwlock.DowngradeFromWriterLock(ref lc); rwlock.ReleaseReaderLock(); }
/// <devdoc> /// Removes an image from the image manager so it is no longer animated. /// </devdoc> public static void StopAnimate(Image image, EventHandler onFrameChangedHandler) { // Make sure we have a list of images if (image == null || imageInfoList == null) { return; } // Acquire a writer lock to modify the image info list - See comments on Animate() about this locking. bool readerLockHeld = rwImgListLock.IsReaderLockHeld; LockCookie lockDowngradeCookie = new LockCookie(); threadWriterLockWaitCount++; try { if (readerLockHeld) { lockDowngradeCookie = rwImgListLock.UpgradeToWriterLock(Timeout.Infinite); } else { rwImgListLock.AcquireWriterLock(Timeout.Infinite); } } finally { threadWriterLockWaitCount--; Debug.Assert(threadWriterLockWaitCount >= 0, "threadWriterLockWaitCount less than zero."); } try { // Find the corresponding reference and remove it for (int i = 0; i < imageInfoList.Count; i++) { ImageInfo imageInfo = imageInfoList[i]; if (image == imageInfo.Image) { if ((onFrameChangedHandler == imageInfo.FrameChangedHandler) || (onFrameChangedHandler != null && onFrameChangedHandler.Equals(imageInfo.FrameChangedHandler))) { imageInfoList.Remove(imageInfo); } break; } } } finally { if (readerLockHeld) { rwImgListLock.DowngradeFromWriterLock(ref lockDowngradeCookie); } else { rwImgListLock.ReleaseWriterLock(); } } }
protected override void InternalDispose(bool isDisposing) { if (!this.disposed) { if (isDisposing) { this.HandleFinishRequestFromClient(); if (this.pendingRequestAliveTimer != null) { this.pendingRequestAliveTimer.Dispose(); this.pendingRequestAliveTimer = null; } if (this.pendingRequestEventHandler != null && !this.pendingRequestEventHandler.IsDisposed && this.lockTracker.TryReleaseAllLocks(new PendingNotifierLockTracker.ReleaseAllLocksCallback(this.pendingRequestEventHandler.Dispose))) { this.pendingRequestEventHandler.Dispose(); } this.pendingRequestEventHandler = null; LockCookie?lockCookie = null; try { try { this.notifiersStateLock.LockWriterElastic(5000); } catch (OwaLockTimeoutException) { ExTraceGlobals.NotificationsCallTracer.TraceDebug((long)this.GetHashCode(), "Dispose was called but the writer lock is not available:"); return; } foreach (KeyValuePair <IPendingRequestNotifier, PendingRequestManager.PendingNotifierState> keyValuePair in this.notifierDataAvaiableState) { keyValuePair.Value.Dispose(); } } finally { if (this.notifiersStateLock.IsWriterLockHeld) { if (lockCookie != null) { LockCookie value = lockCookie.Value; this.notifiersStateLock.DowngradeFromWriterLock(ref value); } else { this.notifiersStateLock.ReleaseWriterLock(); } } if (lockCookie != null && !this.notifiersStateLock.IsReaderLockHeld) { ExAssert.RetailAssert(true, "Lost readerwriterlock that was acquired before entering the method"); } } } this.disposed = true; } }
/// <summary> /// Find the materials used in one Face, and add them to 'm_regionMaterials'. /// </summary> private void GetStoredMaterialInFace(SceneObjectPart part, Primitive.TextureEntryFace face) { UUID id = face.MaterialID; if (id == UUID.Zero) { return; } m_regionMaterialsRwLock.AcquireReaderLock(-1); try { if (m_regionMaterials.ContainsKey(id)) { return; } byte[] data = m_scene.AssetService.GetData(id.ToString()); if (data == null) { m_log.WarnFormat("[Materials]: Prim \"{0}\" ({1}) contains unknown material ID {2}", part.Name, part.UUID, id); return; } OSDMap mat; try { mat = (OSDMap)OSDParser.DeserializeLLSDXml(data); } catch (Exception e) { m_log.WarnFormat("[Materials]: cannot decode material asset {0}: {1}", id, e.Message); return; } LockCookie lc = m_regionMaterialsRwLock.UpgradeToWriterLock(-1); try { if (m_regionMaterials.ContainsKey(id)) { return; } m_regionMaterials[id] = mat; } finally { m_regionMaterialsRwLock.DowngradeFromWriterLock(ref lc); } } finally { m_regionMaterialsRwLock.ReleaseReaderLock(); } }
public void Upgrade() { if (_lockMode != IICLockMode.ReaderLock) { throw new InvalidOperationException("lock mode can't upgraded:" + _lockMode); } _lockCookie = _innerLock.UpgradeToWriterLock(_msTimeout); _lockMode = IICLockMode.UpdatedWriterLock; }
/// <summary> /// Downgrades from writer lock. /// </summary> public virtual void DowngradeFromWriterLock() { if (m_UpgradeLockCookie != null) { m_SynchronizeType = ReaderWriterLockSynchronizeType.Read; LockCookie tempCookie = m_UpgradeLockCookie.Value; m_Root.Sync.DowngradeFromWriterLock(ref tempCookie); m_UpgradeLockCookie = null; } }
public void Bug_55909_Thread2() { rwlock.AcquireReaderLock(Timeout.Infinite); try { Thread.Sleep(1000); LockCookie lc = rwlock.UpgradeToWriterLock(Timeout.Infinite); Thread.Sleep(500); } finally { rwlock.ReleaseReaderLock(); } }
private void ReleaseLock(LockCookie cookie, WriteLock wl) { if (wl != null) { wl.Dispose(); } else { this.StreamsLock.DowngradeFromWriterLock(ref cookie); } }
public void UpgradeToWriterLock() { try { } finally { this.lc = this.locker.UpgradeToWriterLock(this.timeout); this.upgraded = true; } }
public void UpgradeToWriterLock() { Fx.Assert(!forWrite, "Invalid call to Upgrade!!"); Fx.Assert(!upgraded, "Already upgraded!"); try { } finally { lc = locker.UpgradeToWriterLock(timeout); upgraded = true; } }
/// <summary> /// Opens the log file for the current application. /// </summary> /// <param name="logFile">Log file for the current application; if null or string.Empty use the default log file.</param> /// <param name="loggerSetup">LoggerSetup info for the logger instance; if null use the default LoggerSetup info.</param> /// <returns>Logger instance.</returns> public static Logger Open(string logFile, LoggerSetup loggerSetup) { LogConfig logConfig = new LogConfig(); if (!string.IsNullOrEmpty(logFile)) { logConfig.LogFile = logFile; } if (loggerSetup != null) { logConfig.LoggerSetup = loggerSetup; } int key = logConfig.GetHashCode(); Lock.AcquireReaderLock(Timeout.Infinite); try { if (LoggerDictionary.ContainsKey(key)) { return(LoggerDictionary[key]); } else { LockCookie lockCookie = Lock.UpgradeToWriterLock(Timeout.Infinite); try { if (LoggerDictionary.ContainsKey(key)) { return(LoggerDictionary[key]); } else { Logger result = new Logger(logConfig); LoggerDictionary.Add(key, result); return(result); } } finally { Lock.DowngradeFromWriterLock(ref lockCookie); } } } finally { Lock.ReleaseReaderLock(); } }
/// <summary> /// Implements IOutboundTransport.UnsubscribeClient /// </summary> public void UnsubscribeClient(string clientId) { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } if (string.IsNullOrEmpty(clientId)) { throw new ArgumentNullException("clientId"); } TlsClient client = null; _listLock.AcquireReaderLock(DEFAULT_JOIN_TIMEOUT); try { if (!_clients.ContainsKey(clientId)) { throw new TransportException("Client not subscribed to transport"); } client = _clients[clientId]; //Remove LockCookie ck = _listLock.UpgradeToWriterLock(DEFAULT_JOIN_TIMEOUT); try { _clients.Remove(clientId); } finally { _listLock.DowngradeFromWriterLock(ref ck); } } finally { _listLock.ReleaseReaderLock(); if (client != null) { try { client.Stream.Flush(); } catch { } finally { client.Dispose(); } } } }
public void RestoreLock(LockCookie& lockCookie) { }
public void DowngradeFromWriterLock(ref LockCookie lockCookie) { this.DowngradeFromWriterLockInternal(ref lockCookie); }
// Release all locks for the current thread and save them. public LockCookie ReleaseLock() { lock(this) { // Get the lock information for this thread. LockInfo info = GetLockInfo(); if(info == null) { return new LockCookie (LockCookie.CookieType.None, Thread.CurrentThread, 0, 0); } // Bail out if the thread doesn't have any locks. if(info.numReadLocks == 0 && info.numWriteLocks == 0) { return new LockCookie (LockCookie.CookieType.None, Thread.CurrentThread, 0, 0); } // Copy the lock infomation into the cookie. LockCookie cookie = new LockCookie (LockCookie.CookieType.Saved, Thread.CurrentThread, info.numReadLocks, info.numWriteLocks); // Release the active locks. numReadLocks -= info.numReadLocks; numWriteLocks -= info.numWriteLocks; info.numReadLocks = 0; info.numWriteLocks = 0; // Determine if we need to wake up a waiting thread. if(numReadLocks == 0 || numWriteLocks == 0) { Monitor.Pulse(this); } // Return the cookie to the caller. return cookie; } }
// Downgrade the current thread from a writer lock. public void DowngradeFromWriterLock(ref LockCookie lockCookie) { lock(this) { // Get the lock information for this thread. LockInfo info = GetLockInfo(); if(info == null) { return; } // Bail out if the cookie is not "Upgrade". if(lockCookie.type != LockCookie.CookieType.Upgrade || lockCookie.thread != Thread.CurrentThread) { return; } // Restore the thread to its previous lock state. RestoreLockState(info, lockCookie.readCount, lockCookie.writeCount); } }
// Update the current thread to a writer lock. public LockCookie UpgradeToWriterLock(int millisecondsTimeout) { LockCookie cookie; if(millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException ("millisecondsTimeout", _("ArgRange_NonNegOrNegOne")); } lock(this) { // Get the lock information for this thread. LockInfo info = GetOrCreateLockInfo(); // Bail out early if we already have the writer lock. if(info.numWriteLocks > 0) { cookie = new LockCookie (LockCookie.CookieType.Upgrade, Thread.CurrentThread, info.numReadLocks, info.numWriteLocks); ++(info.numWriteLocks); ++numWriteLocks; lastWriteSeqNum = ++seqNum; return cookie; } // If we have the read lock, then upgrade it. if(info.numReadLocks > 0) { cookie = new LockCookie (LockCookie.CookieType.Upgrade, Thread.CurrentThread, info.numReadLocks, info.numWriteLocks); info.numWriteLocks += info.numReadLocks; numReadLocks -= info.numReadLocks; numWriteLocks -= info.numReadLocks; info.numReadLocks = 0; lastWriteSeqNum = ++seqNum; return cookie; } // Block while some other thread has the read or write lock. if(millisecondsTimeout == -1) { while(numReadLocks > 0 || numWriteLocks > 0) { if(!Monitor.Wait(this)) { return new LockCookie (LockCookie.CookieType.None, Thread.CurrentThread, 0, 0); } } } else { DateTime expire = DateTime.UtcNow + new TimeSpan(millisecondsTimeout * TimeSpan.TicksPerMillisecond); DateTime now; int ms; while(numReadLocks > 0 || numWriteLocks > 0) { now = DateTime.UtcNow; if(now >= expire) { return new LockCookie (LockCookie.CookieType.None, Thread.CurrentThread, 0, 0); } ms = (int)((expire - now).Ticks / TimeSpan.TicksPerMillisecond); if(!Monitor.Wait(this, ms)) { return new LockCookie (LockCookie.CookieType.None, Thread.CurrentThread, 0, 0); } } } // Update the thread and global write lock counts. cookie = new LockCookie (LockCookie.CookieType.Upgrade, Thread.CurrentThread, info.numReadLocks, info.numWriteLocks); ++(info.numWriteLocks); ++numWriteLocks; lastWriteSeqNum = ++seqNum; return cookie; } }
// Restore all locks for the curent thread to a previous "Release" value. public void RestoreLock(ref LockCookie lockCookie) { lock(this) { // Get the lock information for this thread. LockInfo info = GetLockInfo(); if(info == null) { return; } // Bail out if the cookie is not "Saved" or if // we have prevailing locks at the moment. if(lockCookie.type != LockCookie.CookieType.Saved || lockCookie.thread != Thread.CurrentThread || info.numReadLocks > 0 || info.numWriteLocks > 0) { return; } // Restore the thread to its previous lock state. RestoreLockState(info, lockCookie.readCount, lockCookie.writeCount); } }
public bool Equals(LockCookie obj) {}
public bool Equals(LockCookie obj) { return ((((obj._dwFlags == this._dwFlags) && (obj._dwWriterSeqNum == this._dwWriterSeqNum)) && (obj._wReaderAndWriterLevel == this._wReaderAndWriterLevel)) && (obj._dwThreadID == this._dwThreadID)); }
public void DowngradeFromWriterLock(LockCookie& lockCookie) { }
void ReaderFunc( ) { int ReadL = Interlocked.Increment(ref ReadX); LockCookie upgradeCookie = new LockCookie( ); try { if((rwLock.IsReaderLockHeld)||(rwLock.IsWriterLockHeld)) lock(this) Console.WriteLine(" {0}, Reader -BAD- No Locks should be held now.",ReadL); } catch(Exception e) { lock(this) Console.WriteLine(" {0}, Reader -BAD- (IsReaderLockHeld || IsWriterLockHeld) {1}",ReadL,e.ToString()); failed = 1; } try { lock(this) Console.WriteLine(" {0}, Reader -fyi- Before AcquireReaderLock.",ReadL); rwLock.AcquireReaderLock(1000); lock(this) Console.WriteLine(" {0}, Reader -fyi- After AcquireReaderLock.",ReadL); } catch(Exception e) { lock(this) Console.WriteLine(" {0}, Reader -BAD- (AcquireReaderLock) {1}",ReadL,e.ToString()); failed = 1; } Thread.Sleep(10); try { if(!(rwLock.IsReaderLockHeld)) lock(this) Console.WriteLine(" {0}, Reader -BAD- ReaderLock FALSE",ReadL); lock(this) Console.WriteLine(" {0}, Reader -fyi- Before UpgradeToWriterLock.",ReadL); upgradeCookie = rwLock.UpgradeToWriterLock(1000); lock(this) Console.WriteLine(" {0}, Reader -fyi- After UpgradeToWriterLock.",ReadL); } catch(Exception e) { lock(this) Console.WriteLine(" {0}, Reader -BAD- (UpgradeToWriterLock) {1}",ReadL,e.ToString()); failed = 1; } try { if(rwLock.IsReaderLockHeld) { lock(this) Console.WriteLine(" {0}, Reader -BAD- ReaderLock TRUE",ReadL); } if(!(rwLock.IsWriterLockHeld)) { lock(this) Console.WriteLine(" {0}, Reader -BAD- WriterLock FALSE",ReadL); } lock(this) Console.WriteLine(" {0}, Reader -fyi- Before DowngradeFromWriterLock.",ReadL); rwLock.DowngradeFromWriterLock(ref upgradeCookie); lock(this) Console.WriteLine(" {0}, Reader -fyi- After DowngradeFromWriterLock.",ReadL); } catch(Exception e) { lock(this) Console.WriteLine(" {0}, Reader -BAD- (DowngradeFromWriterLock) {1}",ReadL,e.ToString()); failed = 1; } try { if(rwLock.IsWriterLockHeld) lock(this) Console.WriteLine(" {0}, Reader -BAD- WriterLock TRUE",ReadL); if(!(rwLock.IsReaderLockHeld)) lock(this) Console.WriteLine(" {0}, Reader -BAD- ReaderLock should be held now.",ReadL); lock(this) Console.WriteLine(" {0}, Reader -fyi- Before ReleaseReaderLock.",ReadL); rwLock.ReleaseReaderLock( ); lock(this) Console.WriteLine(" {0}, Reader -fyi- After ReleaseReaderLock.",ReadL); } catch(Exception e) { lock(this) Console.WriteLine(" {0}, Reader -BAD- (ReleaseReaderLock) {1}",ReadL,e.ToString()); failed = 1; } try { if((rwLock.IsReaderLockHeld)||(rwLock.IsWriterLockHeld)) lock(this) Console.WriteLine(" {0}, Reader -BAD- No Locks should be held now.",ReadL); } catch(Exception e) { lock(this) Console.WriteLine(" {0}, Reader - {1}",ReadL,e.ToString()); failed = 1; } }
private extern void RestoreLockInternal(ref LockCookie lockCookie);
private extern void FCallUpgradeToWriterLock(ref LockCookie result, int millisecondsTimeout);
private extern void FCallReleaseLock(ref LockCookie result);
private extern void DowngradeFromWriterLockInternal(ref LockCookie lockCookie);
public LockCookie UpgradeToWriterLock(int millisecondsTimeout) { LockCookie result = new LockCookie(); this.FCallUpgradeToWriterLock(ref result, millisecondsTimeout); return result; }
void WriterFunc( ) { int WriteL = Interlocked.Increment(ref WriteX); LockCookie releaseCookie = new LockCookie( ); int iWriterSeqNum; if((rwLock.IsReaderLockHeld)||(rwLock.IsWriterLockHeld)) lock(this) Console.WriteLine("{0}, Writer -BAD- No Locks should be held now. (I)",WriteL); try { lock(this) Console.WriteLine("{0}, Writer -fyi- Before AcquireWriterLock.",WriteL); rwLock.AcquireWriterLock(1000); lock(this) Console.WriteLine("{0}, Writer -fyi- After AcquireWriterLock.",WriteL); } catch(Exception e) { lock(this) Console.WriteLine("{0}, Writer -BAD- (AcquireWriterLock) {1}",WriteL,e.ToString()); failed = 1; } Thread.Sleep(10); try { if(!(rwLock.IsWriterLockHeld)) lock(this) Console.WriteLine("{0}, Writer -BAD- WriterLock should be held now. (I)",WriteL); iWriterSeqNum = rwLock.WriterSeqNum; lock(this) Console.WriteLine("{0}, Writer -fyi- Before ReleaseLock.",WriteL); releaseCookie = rwLock.ReleaseLock( ); lock(this) Console.WriteLine("{0}, Writer -fyi- After ReleaseLock.",WriteL); if((rwLock.IsReaderLockHeld)||(rwLock.IsWriterLockHeld)) lock(this) Console.WriteLine("{0}, Writer -BAD- No Locks should be held now. (II)",WriteL); lock(this) Console.WriteLine("{0}, Writer -fyi- Before RestoreLock.",WriteL); rwLock.RestoreLock(ref releaseCookie); lock(this) Console.WriteLine("{0}, Writer -fyi- After RestoreLock.",WriteL); if(!(rwLock.IsWriterLockHeld)) lock(this) Console.WriteLine("{0}, Writer -BAD- WriterLock should be held now. (II)",WriteL); lock(this) Console.WriteLine("{0}, Writer -fyi- Before ReleaseWriterLock.",WriteL); rwLock.ReleaseWriterLock( ); lock(this) Console.WriteLine("{0}, Writer -fyi- After ReleaseWriterLock.",WriteL); bool boX; boX = rwLock.AnyWritersSince(iWriterSeqNum); iWriterSeqNum = rwLock.WriterSeqNum; boX = rwLock.AnyWritersSince(iWriterSeqNum); } catch(Exception e) { lock(this) Console.WriteLine("{0}, Writer - {1}",WriteL,e.ToString()); failed = 1; } }
public LockCookie ReleaseLock() { LockCookie result = new LockCookie(); this.FCallReleaseLock(ref result); return result; }
public void RestoreLock(ref LockCookie lockCookie) { this.RestoreLockInternal(ref lockCookie); }
public static bool op_Inequality(LockCookie a, LockCookie b) {}