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(); } }
private static void MacroDropReset() { m_lock.AcquireWriterLock(Timeout.Infinite); try { foreach (KeyValuePair <int, DropInfo> kvp in m_DropInfo) { int templateId = kvp.Key; DropInfo dropInfo = kvp.Value; if (counter > dropInfo.Time && dropInfo.Time > 0) { if (counter % dropInfo.Time == 0) { dropInfo.Count = dropInfo.MaxCount; } } } } catch (Exception e) { if (log.IsErrorEnabled) { log.Error("DropInfoMgr MacroDropReset", e); } } finally { m_lock.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 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; }
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, 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 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); }
// Write to Resource: static void AddNumber(object num) { readerWriterLock.AcquireWriterLock(1000); numbers.Add((int)num); readerWriterLock.ReleaseWriterLock(); }
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); }
/// <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(); }
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); }
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, 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); }
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); }
/* * 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.IsTrue (!rwlock.IsWriterLockHeld, "#1"); rwlock.AcquireWriterLock (500); Assert.IsTrue (rwlock.IsWriterLockHeld, "#2"); RunThread (new ThreadStart (IsWriterLockHeld_2)); rwlock.ReleaseWriterLock (); }
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); }
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(); } } }
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(); }); }
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(); } }
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 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); }
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 ReaderWriter_When2CycleDetected_DoesNotThrows() { ReaderWriterLock rwl = new ReaderWriterLock(); Barrier barrier = new Barrier(2); Action t1 = () => { rwl.AcquireReaderLock(Timeout.Infinite); barrier.SignalAndWait(); rwl.UpgradeToWriterLock(Timeout.Infinite); rwl.ReleaseWriterLock(); }; Action t2 = () => { rwl.AcquireReaderLock(Timeout.Infinite); barrier.SignalAndWait(); Thread.Sleep(500); rwl.ReleaseReaderLock(); }; TestHelpers.InvokeSimultaneouslyAndWait(t1, t2); }
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 }); }
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(); } }
/// <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 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 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); }
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); }
/// <summary> /// 创建日志文件 /// </summary> private void CreatLog() { TextWriter logwrite = null; ReaderWriterLock writelock = new ReaderWriterLock(); try { writelock.AcquireWriterLock(-1); DirectoryInfo directoryInfo = m_fileinfo.Directory; if (directoryInfo != null && !directoryInfo.Exists) { DirectoryInfo 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 void WithWriteLockTimeoutWithExceptionTest() { var l = new ReaderWriterLock(); var e = new AutoResetEvent(false); var lockGetted = false; var t = new Thread(() => { var b = false; try { l.WithWriteLock(() => { lockGetted = true; Assert.IsTrue(l.IsWriterLockHeld); throw new InvalidOperationException(); }, TimeSpan.FromSeconds(5)); } catch (InvalidOperationException) { b = true; } Assert.IsTrue(b); e.Set(); }); l.AcquireWriterLock(100); t.Start(); Thread.Sleep(1000); Assert.IsFalse(lockGetted); l.ReleaseWriterLock(); e.WaitOne(); Assert.IsTrue(lockGetted); Assert.IsFalse(l.IsWriterLockHeld); }
public static IDisposable AcquireWriterLock(ReaderWriterLock rwl) { rwl.AcquireWriterLock(Timeout.Infinite); return new Disposer(() => rwl.ReleaseWriterLock()); }
public void WithWriteLockTimeoutSuccessTest() { var l = new ReaderWriterLock(); var e = new AutoResetEvent(false); var lockGetted = false; var t = new Thread(() => { l.WithWriteLock(() => { lockGetted = true; Assert.IsTrue(l.IsWriterLockHeld); }, TimeSpan.FromSeconds(5)); e.Set(); }); l.AcquireWriterLock(100); t.Start(); Thread.Sleep(1000); Assert.IsFalse(lockGetted); l.ReleaseWriterLock(); e.WaitOne(); Assert.IsTrue(lockGetted); Assert.IsFalse(l.IsWriterLockHeld); }