private static void LockOnReaderWriterLock() { Console.WriteLine("About to lock on the ReaderWriterLock. Debug after seeing \"Signaled to acquire the reader lock.\""); ReaderWriterLock rwLock = new ReaderWriterLock(); ManualResetEvent rEvent = new ManualResetEvent(false); ManualResetEvent pEvent = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem((object state) => { rwLock.AcquireWriterLock(-1); Console.WriteLine("Writer lock acquired!"); rEvent.Set(); pEvent.WaitOne(); }); rEvent.WaitOne(); Console.WriteLine("Signaled to acquire the reader lock."); rwLock.AcquireReaderLock(-1); Console.WriteLine("Reader lock acquired"); pEvent.Set(); Console.WriteLine("About to end the program. Press any key to exit."); Console.ReadKey(); }
public static bool ReLoadMap() { try { Dictionary <int, MapPoint> tempMaps = new Dictionary <int, MapPoint>(); Dictionary <int, Map> tempMapInfos = new Dictionary <int, Map>(); if (LoadMap(tempMaps, tempMapInfos)) { m_lock.AcquireWriterLock(Timeout.Infinite); try { _maps = tempMaps; _mapInfos = tempMapInfos; return(true); } catch { } finally { m_lock.ReleaseWriterLock(); } } } catch (Exception e) { if (log.IsErrorEnabled) { log.Error("ReLoadMap", e); } } return(false); }
/// <summary> /// 清除已有连接 /// </summary> public void Clear() { try { socketLock.AcquireWriterLock(-1); for (int i = 0; i < _dictSocket.Count; i++) { string strKey = _dictSocket.ElementAt(i).Key; _dictSocket[strKey].Shutdown(SocketShutdown.Both); _dictSocket[strKey].Close(); _dictSocket[strKey].Dispose(); } _dictSocket.Clear(); _recvLen.Clear(); _recvData.Clear(); _recvByte.Clear(); _dictThread.Clear(); } catch (Exception) { } finally { socketLock.ReleaseWriterLock(); } }
public void ProcessPacket(int index, byte[] image, int row_start, int row_count) { PSMoveSharpCameraFrameSlice slice = new PSMoveSharpCameraFrameSlice(); slice.index = index; slice.image = image; slice.row_start = row_start; slice.row_count = row_count; camera_frame_state_rwl.AcquireWriterLock(-1); camera_frame_state_collector.AddSlice(slice); camera_frame_state_rwl.ReleaseWriterLock(); }
private void IRCInputProcedure() { Queue <string> events; while (!StopThreads) { if (!netStream.DataAvailable) { System.Threading.Thread.Sleep(100); continue; } inLock.AcquireWriterLock(100); messages.Enqueue(read.ReadLine()); input = messages.ToArray()[messages.Count - 1]; inLock.ReleaseWriterLock(); //Debug.Log(input); if (input.Split(' ')[1] == "001") { outLock.AcquireWriterLock(100); outputQueue.Enqueue("JOIN #" + channel); outLock.ReleaseWriterLock(); } else if (input.Split(' ')[0] == "PING") { input.Replace("PING", "PONG"); outLock.AcquireWriterLock(100); outputQueue.Enqueue(buffer); outLock.ReleaseWriterLock(); } else { if (input.Split(':').Length < 3) { continue; } input = input.Split(':')[2]; Debug.Log(input); if (input[0] == '!') { events = new Queue <string>(); events.Enqueue("ChangeColor"); events.Enqueue(input.Substring(1).ToLower()); inLock.AcquireWriterLock(100); eventQueue.Enqueue(events); inLock.ReleaseWriterLock(); } } } }
public static bool ReLoad() { try { Dictionary <int, StrengthenInfo> tempStrengthens = new Dictionary <int, StrengthenInfo>(); Dictionary <int, StrengthenInfo> tempRefineryStrengthens = new Dictionary <int, StrengthenInfo>(); Dictionary <int, StrengthenGoodsInfo> tempStrengthenGoodsInfos = new Dictionary <int, StrengthenGoodsInfo>(); if (LoadStrengthen(tempStrengthens, tempRefineryStrengthens)) { m_lock.AcquireWriterLock(Timeout.Infinite); try { _strengthens = tempStrengthens; m_Refinery_Strengthens = tempRefineryStrengthens; Strengthens_Goods = tempStrengthenGoodsInfos; return(true); } catch { } finally { m_lock.ReleaseWriterLock(); } } } catch (Exception e) { if (log.IsErrorEnabled) { log.Error("StrengthenMgr", e); } } return(false); }
/// <summary> /// Removes all event handlers /// </summary> /// <param name="deep">Specifies if all local registered event handlers /// should also be removed</param> public static void RemoveAllHandlers(bool deep) { if (deep) { try { m_lock.AcquireWriterLock(TIMEOUT); try { m_GameObjectEventCollections.Clear(); } finally { m_lock.ReleaseWriterLock(); } } catch (ApplicationException ex) { if (log.IsErrorEnabled) { log.Error("Failed to remove all local event handlers!", ex); } } } m_GlobalHandlerCollection.RemoveAllHandlers(); }
// Write to Resource: static void AddNumber(object num) { readerWriterLock.AcquireWriterLock(1000); numbers.Add((int)num); readerWriterLock.ReleaseWriterLock(); }
public static bool ReLoad() { try { Dictionary <int, ConsortiaLevelInfo> tempConsortiaLevel = new Dictionary <int, ConsortiaLevelInfo>(); if (Load(tempConsortiaLevel)) { m_lock.AcquireWriterLock(Timeout.Infinite); try { _consortiaLevel = tempConsortiaLevel; return(true); } catch { } finally { m_lock.ReleaseWriterLock(); } } } catch (Exception e) { if (log.IsErrorEnabled) { log.Error("ConsortiaLevelMgr", e); } } return(false); }
internal OletxResourceManager RegisterResourceManager( Guid resourceManagerIdentifier ) { OletxResourceManager oletxResourceManager = null; resourceManagerHashTableLock.AcquireWriterLock(-1); try { // If this resource manager has already been registered, don't register it again. oletxResourceManager = resourceManagerHashTable[resourceManagerIdentifier] as OletxResourceManager; if (null != oletxResourceManager) { return(oletxResourceManager); } oletxResourceManager = new OletxResourceManager( this, resourceManagerIdentifier ); resourceManagerHashTable.Add( resourceManagerIdentifier, oletxResourceManager ); } finally { resourceManagerHashTableLock.ReleaseWriterLock(); } return(oletxResourceManager); }
public static bool Reload() { try { Dictionary <int, ItemTemplateInfo> tempProp = new Dictionary <int, ItemTemplateInfo>(); if (LoadProps(tempProp)) { m_lock.AcquireWriterLock(Timeout.Infinite); try { _allProp = tempProp; return(true); } catch { } finally { m_lock.ReleaseWriterLock(); } } } catch (Exception e) { if (log.IsErrorEnabled) { log.Error("ReloadProps", e); } } return(false); }
public static bool ReLoad() { try { Dictionary <int, FightRateInfo> tempfightRate = new Dictionary <int, FightRateInfo>(); if (LoadFightRate(tempfightRate)) { m_lock.AcquireWriterLock(Timeout.Infinite); try { _fightRate = tempfightRate; return(true); } catch { } finally { m_lock.ReleaseWriterLock(); } } } catch (Exception e) { if (log.IsErrorEnabled) { log.Error("AwardMgr", e); } } return(false); }
public static string getOneCell() { string encodedOrder=null; readSem.WaitOne();// wait until buffer cell is not empty then only read ReaderWriterLock rw=new ReaderWriterLock(); rw.AcquireWriterLock(Timeout.Infinite); try{ //reading from buffer --- ciruclar queue if (front_read == bufferSize - 1) front_read = 0; else { front_read = front_read + 1; } encodedOrder = buffer[front_read]; buffer[front_read] = string.Empty; String[] arr=encodedOrder.Split('#'); Console.WriteLine(" chicken farm got an order from {0} of {1} chicken",arr[0],arr[2]); } catch (Exception e){ Console.WriteLine(""); } finally { rw.ReleaseWriterLock(); writeSem.Release(); } return encodedOrder; }
public static bool ReLoad() { try { Dictionary <int, BallInfo> tempBalls = new Dictionary <int, BallInfo>(); Dictionary <int, Tile> tempBallTile = new Dictionary <int, Tile>(); if (LoadBall(tempBalls, tempBallTile)) { m_lock.AcquireWriterLock(Timeout.Infinite); try { _balls = tempBalls; _ballTile = tempBallTile; return(true); } catch { } finally { m_lock.ReleaseWriterLock(); } } } catch (Exception e) { if (log.IsErrorEnabled) { log.Error("BallMgr", e); } } return(false); }
public static bool ReLoad() { try { Dictionary <int, DailyAwardInfo> tempDaily = new Dictionary <int, DailyAwardInfo>(); if (LoadDailyAward(tempDaily)) { m_lock.AcquireWriterLock(Timeout.Infinite); try { _dailyAward = tempDaily; return(true); } catch { } finally { m_lock.ReleaseWriterLock(); } } } catch (Exception e) { if (log.IsErrorEnabled) { log.Error("AwardMgr", e); } } return(false); }
/// <summary> /// 创建日志文件 /// </summary> private void CreatLog() { TextWriter logwrite = null; var writelock = new ReaderWriterLock(); try { writelock.AcquireWriterLock(-1); var directoryInfo = m_fileinfo.Directory; if (directoryInfo != null && !directoryInfo.Exists) { var directory = m_fileinfo.Directory; if (directory != null) directory.Create(); } logwrite = TextWriter.Synchronized(m_fileinfo.CreateText()); logwrite.WriteLine("#------------------------------------------------------"); logwrite.WriteLine("# SYSTEM LOG "); logwrite.WriteLine("# "); logwrite.WriteLine("# Create at " + DateTime.Now.ToString(CultureInfo.InvariantCulture) + " "); logwrite.WriteLine("# "); logwrite.WriteLine("#------------------------------------------------------"); logwrite.Close(); } catch (Exception ex) { throw new Exception("创建系统日志文件出错!" + ex); } finally { writelock.ReleaseWriterLock(); if (logwrite != null) { logwrite.Close(); } } }
public static bool ReLoad() { try { Dictionary <string, FusionInfo> tempFusions = new Dictionary <string, FusionInfo>(); if (LoadFusion(tempFusions)) { m_lock.AcquireWriterLock(Timeout.Infinite); try { _fusions = tempFusions; return(true); } catch { } finally { m_lock.ReleaseWriterLock(); } } } catch (Exception e) { if (log.IsErrorEnabled) { log.Error("FusionMgr", e); } } return(false); }
/* * public string GetAlarmString() * { * try * { * SyncRoot.AcquireReaderLock(-1); * * System.Text.StringBuilder alarmstring = new System.Text.StringBuilder(); * alarmstring.Append("<++++>\r\n"); * alarmstring.Append("COMMAND = ALARM_REPORT\r\n"); * alarmstring.Append("集中告警流水号 = "); * alarmstring.Append(TKSn.ToString()); * alarmstring.Append("\r\n"); * alarmstring.Append("厂商告警流水号 = "); * alarmstring.Append(ManuSn); * alarmstring.Append("\r\n"); * alarmstring.Append("告警城市 = "); * alarmstring.Append(City); * alarmstring.Append("\r\n"); * alarmstring.Append("设备厂商 = "); * alarmstring.Append(Manufacturer); * alarmstring.Append("\r\n"); * alarmstring.Append("业务类型 = "); * alarmstring.Append(BusinessType); * alarmstring.Append("\r\n"); * alarmstring.Append("网元名称 = "); * alarmstring.Append(NeName); * alarmstring.Append("\r\n"); * alarmstring.Append("网元类型 = "); * alarmstring.Append(NeType); * alarmstring.Append("\r\n"); * alarmstring.Append("对象名称 = "); * alarmstring.Append(ObjName); * alarmstring.Append("\r\n"); * alarmstring.Append("对象类型 = "); * alarmstring.Append(ObjType); * alarmstring.Append("\r\n"); * alarmstring.Append("告警名称 = "); * alarmstring.Append(AlarmName); * alarmstring.Append("\r\n"); * alarmstring.Append("重定义告警名称 = "); * alarmstring.Append(Redefinition); * alarmstring.Append("\r\n"); * //alarmstring.Append("告警种类 = "); * //alarmstring.Append(Category); * //alarmstring.Append("\r\n"); * alarmstring.Append("告警级别 = "); * alarmstring.Append(Severity); * alarmstring.Append("\r\n"); * alarmstring.Append("告警发生时间 = "); * alarmstring.Append(OccurTime); * alarmstring.Append("\r\n"); * alarmstring.Append("告警确认时间LV1 = "); * alarmstring.Append(AckTimeLV1); * alarmstring.Append("\r\n"); * alarmstring.Append("再次确认时间LV1 = "); * alarmstring.Append(AckAgainTimeLV1); * alarmstring.Append("\r\n"); * alarmstring.Append("告警确认时间LV2 = "); * alarmstring.Append(AckTimeLV2); * alarmstring.Append("\r\n"); * alarmstring.Append("再次确认时间LV2 = "); * alarmstring.Append(AckAgainTimeLV2); * alarmstring.Append("\r\n"); * alarmstring.Append("告警恢复时间 = "); * alarmstring.Append(ClearTime); * alarmstring.Append("\r\n"); * alarmstring.Append("告警定位信息 = "); * alarmstring.Append(Location); * alarmstring.Append("\r\n"); * alarmstring.Append("操作员信息LV11 = "); * alarmstring.Append(OperatorLV11); * alarmstring.Append("\r\n"); * alarmstring.Append("操作员信息LV12 = "); * alarmstring.Append(OperatorLV12); * alarmstring.Append("\r\n"); * alarmstring.Append("操作员信息LV21 = "); * alarmstring.Append(OperatorLV21); * alarmstring.Append("\r\n"); * alarmstring.Append("操作员信息LV22 = "); * alarmstring.Append(OperatorLV22); * alarmstring.Append("\r\n"); * alarmstring.Append("工程上报信息 = "); * alarmstring.Append(ProjectInfo); * alarmstring.Append("\r\n"); * alarmstring.Append("派单人LV1 = "); * alarmstring.Append(OrderOperatorLV1); * alarmstring.Append("\r\n"); * alarmstring.Append("派单号LV1 = "); * alarmstring.Append(OrderIDLV1); * alarmstring.Append("\r\n"); * alarmstring.Append("派单时间LV1 = "); * alarmstring.Append(OrderTimeLV1); * alarmstring.Append("\r\n"); * alarmstring.Append("派单人LV2 = "); * alarmstring.Append(OrderOperatorLV2); * alarmstring.Append("\r\n"); * alarmstring.Append("派单号LV2 = "); * alarmstring.Append(OrderIDLV2); * alarmstring.Append("\r\n"); * alarmstring.Append("派单时间LV2 = "); * alarmstring.Append(OrderTimeLV2); * alarmstring.Append("\r\n"); * alarmstring.Append("OMCName = "); * alarmstring.Append(OMCName); * alarmstring.Append("\r\n"); * alarmstring.Append("Reserved2 = "); * alarmstring.Append(Reserved2); * alarmstring.Append("\r\n"); * alarmstring.Append("Reserved3 = "); * alarmstring.Append(Reserved3); * alarmstring.Append("\r\n"); * alarmstring.Append("接收时间 = "); * alarmstring.Append(ReceiveTime); * alarmstring.Append("\r\n"); * alarmstring.Append("<---->\r\n"); * * return alarmstring.ToString(); * } * finally * { * SyncRoot.ReleaseReaderLock(); * } * } * */ #endregion public void ConvertFromDB(DataRow dr) { try { SyncRoot.AcquireWriterLock(-1); TKSn = Convert.ToUInt64(dr["TKsn"].ToString()); ManuSn = dr["ManuSn"].ToString().Trim(); City = dr["City"].ToString().Trim(); Manufacturer = dr["Manufacturer"].ToString().Trim(); BusinessType = dr["BusinessType"].ToString().Trim(); NeName = dr["NeName"].ToString().Trim(); NeType = dr["NeType"].ToString().Trim(); ObjName = dr["ObjName"].ToString().Trim(); ObjType = dr["ObjType"].ToString().Trim(); AlarmName = dr["AlarmName"].ToString().Trim(); Redefinition = dr["Redefinition"].ToString().Trim(); Severity = dr["Severity"].ToString().Trim(); OccurTime = dr["OccurTime"].ToString().Trim(); AckTimeLV1 = dr["AckTimeLV1"].ToString().Trim(); AckAgainTimeLV1 = dr["AckAgainTimeLV1"].ToString().Trim(); AckTimeLV2 = dr["AckTimeLV2"].ToString().Trim(); AckAgainTimeLV2 = dr["AckAgainTimeLV2"].ToString().Trim(); ClearTime = dr["ClearTime"].ToString().Trim(); Location = dr["Location"].ToString().Trim(); OperatorLV11 = dr["OperatorLV11"].ToString().Trim(); OperatorLV12 = dr["OperatorLV12"].ToString().Trim(); OperatorLV21 = dr["OperatorLV21"].ToString().Trim(); OperatorLV22 = dr["OperatorLV22"].ToString().Trim(); ProjectInfo = dr["ProjectInfo"].ToString().Trim(); OrderOperatorLV1 = dr["OrderOperatorLV1"].ToString().Trim(); OrderIDLV1 = dr["OrderIDLV1"].ToString().Trim(); OrderTimeLV1 = dr["OrderTimeLV1"].ToString().Trim(); OrderOperatorLV2 = dr["OrderOperatorLV2"].ToString().Trim(); OrderIDLV2 = dr["OrderIDLV2"].ToString().Trim(); OrderTimeLV2 = dr["OrderTimeLV2"].ToString().Trim(); OMCName = dr["OMCName"].ToString().Trim(); Reserved2 = dr["Reserved2"].ToString().Trim(); Reserved3 = dr["Reserved3"].ToString().Trim(); ReceiveTime = dr["ReceiveTime"].ToString().Trim(); } finally { SyncRoot.ReleaseWriterLock(); } }
public static bool ReLoad() { try { Dictionary <string, int> tempAlly = new Dictionary <string, int>(); Dictionary <int, ConsortiaInfo> tempConsortia = new Dictionary <int, ConsortiaInfo>(); if (Load(tempAlly) && LoadConsortia(tempConsortia)) { m_lock.AcquireWriterLock(Timeout.Infinite); try { _ally = tempAlly; _consortia = tempConsortia; return(true); } catch { } finally { m_lock.ReleaseWriterLock(); } } } catch (Exception e) { if (log.IsErrorEnabled) { log.Error("ConsortiaMgr", e); } } return(false); }
public void TestIsWriterLockHeld () { rwlock = new ReaderWriterLock (); Assert ("a1", !rwlock.IsWriterLockHeld); rwlock.AcquireWriterLock (500); Assert ("a2", rwlock.IsWriterLockHeld); RunThread (new ThreadStart (IsWriterLockHeld_2)); rwlock.ReleaseWriterLock (); }
public void TestIsWriterLockHeld () { rwlock = new ReaderWriterLock (); Assert.IsTrue (!rwlock.IsWriterLockHeld, "#1"); rwlock.AcquireWriterLock (500); Assert.IsTrue (rwlock.IsWriterLockHeld, "#2"); RunThread (new ThreadStart (IsWriterLockHeld_2)); rwlock.ReleaseWriterLock (); }
/// <summary> /// Acquires a writer lock on the list passed /// as argument. /// </summary> /// <param name="list"></param> public WriterLockDisposer(ReaderWriterLock lock_) { if (null == lock_) { throw new ArgumentNullException("lock_"); } lock_.AcquireWriterLock(LockTimeout); _lock = lock_; }
public void DoSth10() { try { myReaderWriterLock.AcquireWriterLock(1000); } finally { myReaderWriterLock.ReleaseWriterLock(); } }
//每两分钟向服务器端报告一次掉落物品数量 private static void OnTimeEvent(object source, ElapsedEventArgs e) { Dictionary <int, int> tempDic = new Dictionary <int, int>(); m_lock.AcquireWriterLock(Timeout.Infinite); try { foreach (KeyValuePair <int, MacroDropInfo> kvp in DropInfoMgr.DropInfo) { int templateId = kvp.Key; MacroDropInfo macroDropInfo = kvp.Value; if (macroDropInfo.SelfDropCount > 0) { tempDic.Add(templateId, macroDropInfo.SelfDropCount); macroDropInfo.SelfDropCount = 0; } } } catch (Exception ex) { if (log.IsErrorEnabled) { log.Error("DropInfoMgr OnTimeEvent", ex); } } finally { m_lock.ReleaseWriterLock(); } if (tempDic.Count > 0) { GSPacketIn pkg = new GSPacketIn((byte)eChatServerPacket.MACRO_DROP); pkg.WriteInt(tempDic.Count); foreach (KeyValuePair <int, int> kvp in tempDic) { pkg.WriteInt(kvp.Key); pkg.WriteInt(kvp.Value); } GameServer.Instance.LoginServer.SendPacket(pkg); } }
public T Update <T>(Action <T> exp) where T : class, IConfiguration { var cfg = Read <T>(); exp.Invoke(cfg); rwl.AcquireWriterLock(TimeSpan.FromSeconds(1)); try { Write(cfg); } catch (Exception x) { throw x; } finally { rwl.ReleaseWriterLock(); } return(cfg); }
virtual public void Stop() { lock (this) { if (Interlocked.Read(ref m_Run) == 0) { return; } if (Interlocked.Exchange(ref m_PendingRun, 0) == 0) { return; } SendLog("正在关闭" + Name + "告警适配器..."); _PreStopStage(); AdapterStateReport(AdapterStatus.Stop, null); if (!AdapterLogout()) { SendLog("从告警服务器注销失败, 服务器中信息可能不正确."); } try { if (m_CommClient != null) { m_CommClient.onConnectionBroken -= new ClientConnectionBrokenHandler(DBAdapterBase_onConnectionBroken); m_CommClient.Close(); } } catch { } m_TimerMaintenance.Stop(); _PostStopStage(); try { m_StopPrivilege.AcquireWriterLock(-1); } finally { m_StopPrivilege.ReleaseLock(); } Interlocked.Exchange(ref m_Run, 0); SendLog(Name + "告警适配器已结束."); } }
public void CantAqureLock() { var l = new ReaderWriterLock(); var e = new AutoResetEvent(false); var t = new Thread(() => { l.AcquireWriterLock(TimeSpan.FromSeconds(1)); e.Set(); Thread.Sleep(TimeSpan.FromMinutes(10)); }); t.Start(); e.WaitOne(); var a = new DisposableReaderWriterLock(l, TimeSpan.FromSeconds(3), LockMode.Write); }
public LockingObject(ReaderWriterLock _lock, AccessMode _lockMode) { readerWriterLock = _lock; accessMode = _lockMode; if (accessMode == AccessMode.Read) { readerWriterLock.AcquireReaderLock(-1); } else { readerWriterLock.AcquireWriterLock(-1); } }
private void IRCInputProcedure() { while (!StopThreads) { if (!netStream.DataAvailable) { System.Threading.Thread.Sleep(100); continue; } buffer = read.ReadLine(); input = buffer; if (buffer.Split(' ')[1] == "001") { foreach (string channel in channels) { sendMessage("JOIN #" + channel.ToLower()); } sendMessage("CAP REQ :twitch.tv/commands"); sendMessage("CAP REQ :twitch.tv/tags"); } else if (input.Split(' ')[0] == "PING") { input.Replace("PING", "PONG"); outlock.AcquireWriterLock(100); outputQueue.Enqueue(input); outlock.ReleaseWriterLock(); } else { inlock.AcquireWriterLock(100); inputQueue.Enqueue(input); inlock.ReleaseWriterLock(); } } }
private WriteLock( ReaderWriterLock syncLock, TimeSpan timeout ) { if( syncLock == null ) throw new ArgumentNullException( "ReaderWriterLock syncLock" ); _rwLock = syncLock; try { syncLock.AcquireWriterLock( timeout ); } catch( ApplicationException ) { _timedOut = true; } }
public static void DoActionWithWriterLock(Action funcToRun) { bool hadReaderLock = false; bool hadWriterLock = false; LockCookie cookie; if (!_lock.IsWriterLockHeld) { if (_lock.IsReaderLockHeld) { hadReaderLock = true; cookie = _lock.UpgradeToWriterLock(_writerLockTimeoutMs); } if (!_lock.IsWriterLockHeld) { _lock.AcquireWriterLock(_writerLockTimeoutMs); } } else { hadWriterLock = true; } if (!_lock.IsWriterLockHeld) { throw new ApplicationException("Unable to acquire WRITER lock on CommandQueue after waiting " + _writerLockTimeoutMs + " milliseconds."); } //do the thing funcToRun(); if (hadWriterLock) { //keep it } else if (hadReaderLock && _lock.IsWriterLockHeld) { //Reset the _lock.DowngradeFromWriterLock(ref cookie); } else { //release it all _lock.ReleaseWriterLock(); } }
public void LockVSReaderWriterLockVSReaderWriterLockSlimVSHandle() { TestName("Lock vs. ReaderWriterLock vs. ReaderWriterLockSlim vs. Handle-based"); Object o = new Object(); CodeTimer.Time("Lock perf: Monitor", iterations, () => { Monitor.Enter(o); // Monitor.Exit(o); }); CodeTimer.Time("Lock perf: Lock", iterations, () => { lock (o) { } }); ReaderWriterLockSlim rwls = new ReaderWriterLockSlim(); CodeTimer.Time("Lock perf: ReaderWriterLockSlim", iterations, () => { rwls.EnterWriteLock(); rwls.ExitWriteLock(); }); ReaderWriterLock rwl = new ReaderWriterLock(); CodeTimer.Time("Lock perf: ReaderWriterLock", iterations, () => { rwl.AcquireWriterLock(Timeout.Infinite); rwl.ReleaseWriterLock(); }); Mutex mutex = new Mutex(); CodeTimer.Time("Lock perf: Mutex", iterations, () => { mutex.WaitOne(); mutex.ReleaseMutex(); }); }
public IICLockRegion(ReaderWriterLock innerLock, IICLockMode mode, int millisecondTimeout) { _innerLock = innerLock; _lockMode = mode; _msTimeout = millisecondTimeout; switch (mode) { case IICLockMode.ReaderLock: _innerLock.AcquireReaderLock(millisecondTimeout); break; case IICLockMode.WriterLock: _innerLock.AcquireWriterLock(millisecondTimeout); break; default: throw new NotSupportedException("Unexcepted LockMode: " + mode); } }
protected override void PurgeCache(object sender, System.Timers.ElapsedEventArgs e) { ReaderWriterLock readWriteLock = new ReaderWriterLock(); //Öncelik olarak ortanın altında seçiyoruz. Çünkü öncelik ekleme, güncelleme gibi işlerde. //Varsın bi kaç saniye geç temizlensin cache Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; if (!Monitor.TryEnter(isPurging)) return; try { readWriteLock.AcquireWriterLock(500); try { List<object> expiredItems = new List<object>(); foreach (CacheKey timedKey in timedStorage.Keys) { if (timedKey.ExpirationDate < e.SignalTime) { // Temizlenmesi için birnevi nesneler işaretlenir. expiredItems.Add(timedKey.Key); } else break; } foreach (object key in expiredItems) { CacheKey timedKey = timedStorageIndex[key]; timedStorageIndex.Remove(timedKey.Key); timedStorage.Remove(timedKey); } } catch (ApplicationException ae) { System.Console.WriteLine("Şu an lock lı."); } finally { readWriteLock.ReleaseWriterLock(); } } finally { Monitor.Exit(isPurging); } }
/// <summary> /// Loads the System Defaults into the cached Typed DataTable. /// /// The System Defaults are retrieved from the s_system_defaults table and are /// put into a Typed DataTable that has the structure of this table. /// /// </summary> /// <returns>void</returns> private void LoadSystemDefaultsTable() { TDataBase DBAccessObj = new Ict.Common.DB.TDataBase(); TDBTransaction ReadTransaction = null; // Prevent other threads from obtaining a read lock on the cache table while we are (re)loading the cache table! FReadWriteLock.AcquireWriterLock(SharedConstants.THREADING_WAIT_INFINITE); try { if (FSystemDefaultsDT != null) { FSystemDefaultsDT.Clear(); } try { DBAccessObj.EstablishDBConnection(TSrvSetting.RDMBSType, TSrvSetting.PostgreSQLServer, TSrvSetting.PostgreSQLServerPort, TSrvSetting.PostgreSQLDatabaseName, TSrvSetting.DBUsername, TSrvSetting.DBPassword, "", "SystemDefaultsCache DB Connection"); DBAccessObj.BeginAutoReadTransaction(IsolationLevel.RepeatableRead, ref ReadTransaction, delegate { FSystemDefaultsDT = SSystemDefaultsAccess.LoadAll(ReadTransaction); }); } finally { DBAccessObj.CloseDBConnection(); } // Thread.Sleep(5000); uncomment this for debugging. This allows checking whether read access to FSystemDefaultsDT actually waits until we release the WriterLock in the finally block. } finally { // Other threads are now free to obtain a read lock on the cache table. FReadWriteLock.ReleaseWriterLock(); } }
/// <summary> /// Creates a new ICache of the specified type. /// </summary> /// <param name="context">The name of the context to create.</param> /// <param name="cacheType">The type of ICache to create.</param> /// <returns>False if the context already exists, true otherwise.</returns> /// <exception cref="System.InvalidCastException">Thrown when type 'cacheType' does not implement GlynnTucker.Cache.ICache</exception> public static bool AddContext(string context, Type cacheType) { ICache newCache = (ICache)Activator.CreateInstance(cacheType); readWriteLock.AcquireWriterLock(MAX_LOCK_WAIT); try { if (caches.ContainsKey(context)) { return(false); } else { caches.Add(context, newCache); return(true); } } finally { readWriteLock.ReleaseWriterLock(); } }
public static void setOneCell(string encodedObject) { writeSem.WaitOne(); //wait until buffer has atleast one space in it ReaderWriterLock rw = new ReaderWriterLock(); rw.AcquireWriterLock(Timeout.Infinite); try{ // writing into buffer --- circular queue if(rear_write==bufferSize-1) rear_write=0; else rear_write=rear_write+1; buffer[rear_write]=encodedObject; } finally { rw.ReleaseWriterLock(); readSem.Release(); } }
/// <summary> /// 写入日志 /// </summary> /// <param name="content"></param> public void WriteLog(string content) { ReaderWriterLock writelock = new ReaderWriterLock(); TextWriter logwrite = null; try { writelock.AcquireWriterLock(-1); logwrite = TextWriter.Synchronized(m_fileinfo.AppendText()); logwrite.Write("\r\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + content + "\r\n"); logwrite.Close(); } catch (Exception ex) { throw new Exception("记录日志发生错误" + ex.Message); } finally { if (logwrite != null) { logwrite.Close(); } writelock.ReleaseWriterLock(); } }
public void AddOrReplace(TKey key, TItem item) { try { _lock.AcquireWriterLock(Timeout.Infinite); _items.Add(key, item); lock (_notifications) { List <ConsumerReadAwaiter> awaiters; if (_notifications.TryGetValue(key, out awaiters)) { foreach (var awaiter in awaiters) { awaiter.SetResult(item); } _notifications.Remove(key); } } } finally { _lock.ReleaseWriterLock(); } }
/// <summary> /// Loads the System Defaults into the cached Typed DataTable. /// /// The System Defaults are retrieved from the s_system_defaults table and are /// put into a Typed DataTable that has the structure of this table. /// /// </summary> /// <returns>void</returns> private void LoadSystemDefaultsTable() { TDBTransaction ReadTransaction; Boolean NewTransaction = false; // Prevent other threads from obtaining a read lock on the cache table while we are (re)loading the cache table! FReadWriteLock.AcquireWriterLock(SharedConstants.THREADING_WAIT_INFINITE); try { if (FSystemDefaultsDT != null) { FSystemDefaultsDT.Clear(); } try { ReadTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead, TEnforceIsolationLevel.eilMinimum, out NewTransaction); FSystemDefaultsDT = SSystemDefaultsAccess.LoadAll(ReadTransaction); } finally { if (NewTransaction) { DBAccess.GDBAccessObj.CommitTransaction(); TLogging.LogAtLevel(7, "TSystemDefaultsCache.LoadSystemDefaultsTable: commited own transaction."); } } // Thread.Sleep(5000); uncomment this for debugging. This allows checking whether read access to FSystemDefaultsDT actually waits until we release the WriterLock in the finally block. } finally { // Other threads are now free to obtain a read lock on the cache table. FReadWriteLock.ReleaseWriterLock(); } }
public static bool CanDrop(int templateId) { if (DropInfo == null) { return(true); } m_lock.AcquireWriterLock(Timeout.Infinite); try { if (DropInfo.ContainsKey(templateId)) { MacroDropInfo mdi = DropInfo[templateId]; if (mdi.DropCount < mdi.MaxDropCount || mdi.SelfDropCount >= mdi.DropCount) { mdi.SelfDropCount++; mdi.DropCount++; return(true); } else { return(false); } } } catch (Exception e) { if (log.IsErrorEnabled) { log.Error("DropInfoMgr CanDrop", e); } } finally { m_lock.ReleaseWriterLock(); } //不包含该物品,直接返回true return(true); }
/// <summary> /// 多线程安全缓存参数类型集合 /// </summary> private PropertyInfo[] GetCacheParamType <T>(T pb) { Type pbtype = pb.GetType(); try { if (cacheParamType.ContainsKey(pbtype)) { return(cacheParamType[pbtype]); } else { lockrw.AcquireWriterLock(1000); if (!cacheParamType.ContainsKey(pbtype)) { PropertyInfo[] pis = pbtype.GetProperties().OrderBy(p => p.Name).ToArray(); cacheParamType.Add(pbtype, pis); return(pis); } else { return(cacheParamType[pbtype]); } } } finally { if (lockrw.IsReaderLockHeld) { lockrw.ReleaseReaderLock(); } if (lockrw.IsWriterLockHeld) { lockrw.ReleaseWriterLock(); } } }
public static bool ReLoad() { try { m_lock.AcquireWriterLock(Timeout.Infinite); try { using (ServiceBussiness db = new ServiceBussiness()) { _RateInfo = db.GetExperienceRate(WorldMgr.ServerID); } if (_RateInfo == null) { _RateInfo = new ExperienceRateInfo(); _RateInfo.Rate = -1; } return(true); } catch { } finally { m_lock.ReleaseWriterLock(); } } catch (Exception e) { if (log.IsErrorEnabled) { log.Error("ExperienceRateMgr", e); } } return(false); }
/// <summary> /// 通用输出并记录,主线程 /// </summary> /// <param name="message"></param> public static void OutputAndSaveTxt(string message) { if (!File.Exists(Path.Combine(TheBasePath, "Alloutput.txt"))) { File.Create(Path.Combine(TheBasePath, "Alloutput.txt")); } ReaderWriterLock rwl = new System.Threading.ReaderWriterLock(); lock (objectLock) { rwl.AcquireWriterLock(1000); Thread.Sleep(new Random().Next(1000, 2000)); Console.WriteLine(message); File.AppendAllLines(Path.Combine(TheBasePath, "Alloutput.txt"), new List <string>() { message }); //File.AppendAllText(Path.Combine(TheBasePath, "Alloutput.txt"), message); Thread.Sleep(new Random().Next(1000, 2000)); rwl.ReleaseWriterLock(); } }
public static IDisposable AsWriter(ReaderWriterLock theLock) { theLock.AcquireWriterLock(Timeout.Infinite); return new RWLockWrapper(new DotNetReaderWriterLock(theLock)); }
public static IDisposable AcquireWriterLock(ReaderWriterLock rwl) { rwl.AcquireWriterLock(Timeout.Infinite); return new Disposer(() => rwl.ReleaseWriterLock()); }
public void ReaderWriter_WhenUpgradedWriteLockReleased_EdgesDeleteFromGraph() { ReaderWriterLock rwl = new ReaderWriterLock(); Barrier barrier = new Barrier(3); Barrier barrier2 = new Barrier(3); Task t1 = new Task(() => { rwl.AcquireReaderLock(Timeout.Infinite); rwl.UpgradeToWriterLock(Timeout.Infinite); rwl.ReleaseWriterLock(); barrier.SignalAndWait(); barrier2.SignalAndWait(); lock (rwl) { Thread.Sleep(100); } }); Task t2 = new Task(() => { barrier.SignalAndWait(); lock (rwl) { barrier2.SignalAndWait(); rwl.AcquireWriterLock(Timeout.Infinite); } }); t1.Start(); t2.Start(); barrier.SignalAndWait(); rwl.AcquireReaderLock(Timeout.Infinite); barrier2.SignalAndWait(); Thread.Sleep(500); rwl.ReleaseReaderLock(); Task.WaitAll(new[] { t1, t2 }); }
public WriteLatch(ReaderWriterLock lck, int timeout) { _mutex = lck; if (_mutex.IsReaderLockHeld) { _upgraded = true; _cookie = lck.UpgradeToWriterLock(timeout); } else { _upgraded = false; lck.AcquireWriterLock(timeout); } }
public WriterLock(ReaderWriterLock rwLock, int millisecondsTimeout) { this.rwLock = rwLock; rwLock.AcquireWriterLock(millisecondsTimeout); }
/// <summary> /// Creates a read lock /// </summary> /// <param name="l"></param> public DisposableWriteLock(ReaderWriterLock l) { m_l = l; l.AcquireWriterLock(Timeout.Infinite); }
public void TestReleaseRestoreWriterLock () { rwlock = new ReaderWriterLock (); rwlock.AcquireWriterLock (500); rwlock.AcquireWriterLock (500); Assert.IsTrue (rwlock.IsWriterLockHeld); LockCookie co = rwlock.ReleaseLock (); RunThread (new ThreadStart (AcquireLock_readerWorks)); rwlock.RestoreLock (ref co); RunThread (new ThreadStart (AcquireLock_readerFails)); rwlock.ReleaseWriterLock (); Assert.IsTrue (rwlock.IsWriterLockHeld); rwlock.ReleaseWriterLock (); Assert.IsTrue (!rwlock.IsWriterLockHeld); }
public void TestReaderMustWaitWriter () { // A thread cannot get the reader lock if there are other threads // waiting for the writer lock. rwlock = new ReaderWriterLock (); rwlock.AcquireWriterLock (200); ThreadRunner tr = StartThread (new ThreadStart (ReaderMustWaitWriter_2)); Thread.Sleep (200); RunThread (new ThreadStart (AcquireLock_readerFails)); rwlock.ReleaseReaderLock (); tr.Join (); }
public void TestReaderInsideWriter () { // Reader acquires and releases work like the writer equivalent rwlock = new ReaderWriterLock (); rwlock.AcquireWriterLock (-1); rwlock.AcquireReaderLock (-1); Assert.IsTrue (!rwlock.IsReaderLockHeld); Assert.IsTrue (rwlock.IsWriterLockHeld); rwlock.AcquireReaderLock (-1); Assert.IsTrue (!rwlock.IsReaderLockHeld); Assert.IsTrue (rwlock.IsWriterLockHeld); rwlock.ReleaseWriterLock (); Assert.IsTrue (!rwlock.IsReaderLockHeld); Assert.IsTrue (rwlock.IsWriterLockHeld); rwlock.ReleaseReaderLock (); Assert.IsTrue (!rwlock.IsReaderLockHeld); Assert.IsTrue (rwlock.IsWriterLockHeld); rwlock.ReleaseReaderLock (); Assert.IsTrue (!rwlock.IsReaderLockHeld); Assert.IsTrue (!rwlock.IsWriterLockHeld); }
internal /*public*/ ReaderWriterLockResource(ReaderWriterLock theLock, bool writerLock) { _lock = theLock; _writerLock = writerLock; if (_writerLock) { _lock.AcquireWriterLock(Timeout.Infinite); } else { _lock.AcquireReaderLock(Timeout.Infinite); } }
public void TestReaderInsideWriter () { // Reader acquires and releases work like the writer equivalent rwlock = new ReaderWriterLock (); rwlock.AcquireWriterLock (-1); rwlock.AcquireReaderLock (-1); Assert ("u1", !rwlock.IsReaderLockHeld); Assert ("u2", rwlock.IsWriterLockHeld); rwlock.AcquireReaderLock (-1); Assert ("u3", !rwlock.IsReaderLockHeld); Assert ("u4", rwlock.IsWriterLockHeld); rwlock.ReleaseWriterLock (); Assert ("u5", !rwlock.IsReaderLockHeld); Assert ("u6", rwlock.IsWriterLockHeld); rwlock.ReleaseReaderLock (); Assert ("u7", !rwlock.IsReaderLockHeld); Assert ("u8", rwlock.IsWriterLockHeld); rwlock.ReleaseReaderLock (); Assert ("u9", !rwlock.IsReaderLockHeld); Assert ("u10", !rwlock.IsWriterLockHeld); }
internal WriterLock(ReaderWriterLock readerWriterLock) { this.readerWriterLock = readerWriterLock; readerWriterLock.AcquireWriterLock(Timeout.Infinite); }
public void TestAcquireLocks () { rwlock = new ReaderWriterLock (); rwlock.AcquireReaderLock (500); rwlock.AcquireReaderLock (500); rwlock.ReleaseReaderLock (); Assert.IsTrue (rwlock.IsReaderLockHeld, "#1"); RunThread (new ThreadStart (AcquireLock_readerWorks)); Assert.IsTrue (rwlock.IsReaderLockHeld); RunThread (new ThreadStart (AcquireLock_writerFails)); rwlock.ReleaseReaderLock (); Assert.IsTrue (!rwlock.IsReaderLockHeld); RunThread (new ThreadStart (AcquireLock_writerWorks)); rwlock.AcquireWriterLock (200); RunThread (new ThreadStart (AcquireLock_writerFails)); RunThread (new ThreadStart (AcquireLock_readerFails)); rwlock.ReleaseWriterLock (); }
public WriteLocker(ref ReaderWriterLock rwl) { mRwl = rwl; mRwl.AcquireWriterLock(Constants.kLockTimoutMs); }
internal OletxTransactionManager( string nodeName ) { lock ( ClassSyncObject ) { // If we have not already initialized the shim factory and started the notification // thread, do so now. if (null == OletxTransactionManager.proxyShimFactory ) { Int32 error = NativeMethods.GetNotificationFactory( OletxTransactionManager.ShimWaitHandle.SafeWaitHandle, out OletxTransactionManager.proxyShimFactory ); if ( 0 != error ) { throw TransactionException.Create( SR.GetString( SR.TraceSourceOletx ), SR.GetString( SR.UnableToGetNotificationShimFactory ), null ); } ThreadPool.UnsafeRegisterWaitForSingleObject( OletxTransactionManager.ShimWaitHandle, new WaitOrTimerCallback( OletxTransactionManager.ShimNotificationCallback ), null, -1, false ); } } this.dtcTransactionManagerLock = new ReaderWriterLock(); this.nodeNameField = nodeName; // The DTC proxy doesn't like an empty string for node name on 64-bit platforms when // running as WOW64. It treats any non-null node name as a "remote" node and turns off // the WOW64 bit, causing problems when reading the registry. So if we got on empty // string for the node name, just treat it as null. if (( null != this.nodeNameField ) && ( 0 == this.nodeNameField.Length )) { this.nodeNameField = null; } if ( DiagnosticTrace.Verbose ) { DistributedTransactionManagerCreatedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ), this.GetType(), this.nodeNameField ); } // Initialize the properties from config. configuredTransactionOptions.IsolationLevel = isolationLevelProperty = TransactionManager.DefaultIsolationLevel; configuredTransactionOptions.Timeout = timeoutProperty = TransactionManager.DefaultTimeout; this.internalResourceManager = new OletxInternalResourceManager( this ); dtcTransactionManagerLock.AcquireWriterLock( -1 ); try { this.dtcTransactionManager = new DtcTransactionManager( this.nodeNameField, this ); } finally { dtcTransactionManagerLock.ReleaseWriterLock(); } if (resourceManagerHashTable == null) { resourceManagerHashTable = new Hashtable(2); resourceManagerHashTableLock = new System.Threading.ReaderWriterLock(); } }
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; } }