public static TimedLock Lock(object o, TimeSpan timeout) { TimedLock result = new TimedLock(o); if (!Monitor.TryEnter(o, timeout)) { Console.WriteLine("Timeout Waiting for lock... @" + o.ToString()); } return result; }
public void ReloadItems() { using (TimedLock.Lock(this.Items)) { Items.Clear(); hashtable_1.Clear(); list_1.Clear(); DataTable dataTable; using (DatabaseClient dbClient = HabboIM.GetDatabase().GetClient()) { dataTable = dbClient.ReadDataTable("SELECT items.Id,items.base_item,items_extra_data.extra_data FROM items LEFT JOIN items_extra_data ON items_extra_data.item_id = items.Id WHERE room_id = 0 AND user_id = " + this.UserId); } if (dataTable != null) { foreach (DataRow row in dataTable.Rows) { string extraData = (row["extra_data"] == DBNull.Value) ? string.Empty : (string)row["extra_data"]; if (extraData != null && !DBNull.Value.Equals(extraData) && !string.IsNullOrEmpty(extraData)) { Items.Add(new UserItem((uint)row["Id"], (uint)row["base_item"], extraData)); } else { Items.Add(new UserItem((uint)row["Id"], (uint)row["base_item"], "")); } } } using (TimedLock.Lock(Pets)) { Pets.Clear(); using (DatabaseClient dbClient = HabboIM.GetDatabase().GetClient()) { dbClient.AddParamWithValue("userid", this.UserId); dataTable = dbClient.ReadDataTable("SELECT Id, user_id, room_id, name, type, race, color, expirience, energy, nutrition, respect, createstamp, x, y, z FROM user_pets WHERE user_id = @userid AND room_id <= 0"); } if (dataTable != null) { foreach (DataRow row in dataTable.Rows) { Pet pet = HabboIM.GetGame().GetCatalog().method_12(row); this.Pets.Add(pet.PetId, pet); } } } } }
private void HandlePortal(Player player, Portal portal) { if (portal == null || !portal.Usable || SetPortalRequirement(player, portal, player.Level) == false) { return; } using (TimedLock.Lock(portal.CreateWorldLock)) { var world = portal.WorldInstance; // special portal case lookup if (world == null && _realmPortals.Contains(portal.ObjectType)) { world = player.Manager.GetRandomGameWorld(); if (world == null) { return; } } if (world is Realm && !player.Manager.Resources.GameData.ObjectTypeToId[portal.ObjectDesc.ObjectType].Contains("Cowardice")) { player.FameCounter.CompleteDungeon(player.Owner.Name); } if (world != null) { player.Reconnect(world); if (portal.WorldInstance?.Invites != null) { portal.WorldInstance.Invites.Remove(player.Name.ToLower()); } if (portal.WorldInstance?.Invited != null) { portal.WorldInstance.Invited.Add(player.Name.ToLower()); } return; } // dynamic case lookup if (portal.CreateWorldTask == null || portal.CreateWorldTask.IsCompleted) { portal.CreateWorldTask = Task.Factory .StartNew(() => portal.CreateWorld(player)) .ContinueWith(e => Log.Error(e.Exception.InnerException.ToString()), TaskContinuationOptions.OnlyOnFaulted); } portal.WorldInstanceSet += player.Reconnect; } }
/// <summary> /// Initiates a network connection to the message router at the /// specified network endpoint and then initiates the transmission /// of the message once the connection is established. /// </summary> /// <param name="ep">The remote router's endpoint.</param> /// <param name="msg">The message to be sent (or <c>null</c>).</param> public void Connect(IPEndPoint ep, Msg msg) { using (TimedLock.Lock(router.SyncRoot)) { Assertion.Test(sock == null); sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); localEP = new ChannelEP(Transport.Tcp, router.NormalizeEP(router.TcpEP)); sock.NoDelay = !router.TcpDelay; sock.SendBufferSize = router.TcpSockConfig.SendBufferSize; sock.ReceiveBufferSize = router.TcpSockConfig.ReceiveBufferSize; if (router.FragmentTcp) { sock.SendMax = 1; sock.ReceiveMax = 1; } // Queue the channel initialization message and the message passed Msg initMsg; initMsg = new TcpInitMsg(router.RouterEP, new MsgRouterInfo(router), isUplink, router.TcpEP.Port); initMsg._TTL = 1; Serialize(initMsg); Enqueue(initMsg); try { SetLastAccess(); remoteEP = new ChannelEP(Transport.Tcp, router.NormalizeEP(ep)); if (msg != null) { msg._SetToChannel(remoteEP); msg._SetFromChannel(localEP); msg._Trace(router, 2, "TCP: Queue", null); Serialize(msg); Enqueue(msg); } router.Trace(2, "TCP: Outbound", "LocalEP=" + localEP.NetEP.ToString() + " remoteEP=" + remoteEP.NetEP.ToString(), null); sock.BeginConnect(remoteEP.NetEP, new AsyncCallback(OnConnect), null); } catch (Exception e) { router.Trace(string.Format(null, "TCP: Connect Failed [{0}]", ep), e); router.OnTcpClose(this); Close(); } } }
/// <summary> /// Registers a <see cref="DynDnsHostEntry" /> with the Dynamic DNS cluster. /// </summary> /// <param name="hostEntry">The host/IP address <see cref="DynDnsHostEntry" /> to be registered.</param> /// <remarks> /// <note> /// This method does not throw an exception if the registration is already registered. /// </note> /// </remarks> /// <exception cref="InvalidOperationException">Thrown if the client has not been started.</exception> public void Register(DynDnsHostEntry hostEntry) { using (TimedLock.Lock(syncLock)) { if (!hosts.ContainsKey(hostEntry)) { hosts[hostEntry] = hostEntry; Register(); } } }
public void BasicTimedLockTest() { ThreadedRepeat(10, index => { object lockTarget = new object(); using (TimedLock.Lock(lockTarget)) { Thread.Sleep(400); } }); }
public DateTime ScheduleRequest() { using (TimedLock.Lock(_concurrencyLock)) { _lastRequestScheduledTime = _lastRequestScheduledTime < DateTime.UtcNow.AddSeconds(_secondsPerRequest) ? DateTime.UtcNow : _lastRequestScheduledTime.AddSeconds(_secondsPerRequest); return(_lastRequestScheduledTime); } }
/// <summary> /// Updates the send queue parameters. /// </summary> /// <param name="countLimit">The maximum number of normal priority messages to queue.</param> /// <param name="sizeLimit">The maximum bytes of serialized normal priority messages to queue.</param> public void SetQueueLimits(int countLimit, int sizeLimit) { using (TimedLock.Lock(router.SyncRoot)) { if (sendQueue != null) { sendQueue.CountLimit = countLimit; sendQueue.SizeLimit = sizeLimit; } } }
/// <summary> /// Readies the class to accept ServiceControl commands. /// </summary> /// <remarks> /// This must be called when the derived class is instantiated. /// </remarks> public void Open() { using (TimedLock.Lock(this)) { inbox = new SharedMemInbox(); inbox.Open(ServiceControl.ServiceMemPrefix + service.Name, ServiceControl.MaxMsgSize, new SharedMemInboxReceiveDelegate(OnReceive)); outbox = new SharedMemOutbox(ServiceControl.MaxMsgSize, ServiceControl.MaxWaitTime); } }
/// <summary> /// Closes the log file if it's open. /// </summary> public void Close() { using (TimedLock.Lock(this)) { if (file != null) { file.Close(); file = null; } } }
public static void RunOnIdle(IdleCallback callBack, object state = null, double delayInSeconds = 0) { if (!timer.IsRunning) { timer.Start(); } using (TimedLock.Lock(functionsToCallOnIdle, "PendingUiEvents AddAction()")) { functionsToCallOnIdle.Add(new CallBackAndState(callBack, state, timer.ElapsedMilliseconds + (int)(delayInSeconds * 1000))); } }
public void TimedLockFromSecondsTest() { ThreadedRepeat(10, index => { object lockTarget = new object(); using (TimedLock.LockForSeconds(lockTarget, 1)) { Thread.Sleep(200); } }); }
public static TimedLock TryLock(object o, out bool gotLock, string hint) { TimedLock timedLock = new TimedLock(o, hint); if (!Monitor.TryEnter(o, 1)) { timedLock.gotLock = false; } gotLock = timedLock.gotLock; return timedLock; }
/// <summary> /// Immediately terminates the processing of all client messages. /// </summary> public void Stop() { using (TimedLock.Lock(router.SyncRoot)) { if (router != null) { router.Dispatcher.RemoveTarget(this); router = null; } } }
/// <summary> /// Closes the topology, releasing all resources. /// </summary> /// <remarks> /// <note> /// It is not an error to call this method if the cluster /// is already closed. /// </note> /// </remarks> public virtual void Close() { using (TimedLock.Lock(this)) { if (router != null) { router.LogicalRouteChange -= onLogicalChange; // Disable these notifications router = null; } } }
/// <summary> /// Sets an <see cref="IOperationLog" />'s mode to <see cref="OperationLogMode.Redo" /> /// and then closes the log. /// </summary> /// <param name="operationLog">The <see cref="IOperationLog" />.</param> /// <remarks> /// This is called when the base transaction is committed and all of the /// operations that compose the transaction have been persisted to the /// log. The method sets the operation log mode to <see cref="OperationLogMode.Redo" /> /// so that the operations will be reapplied after a process crash. /// </remarks> public void CommitOperationLog(IOperationLog operationLog) { using (TimedLock.Lock(syncLock)) { if (!isOpen) { throw new TransactionException(NotOpenMsg); } ((MemoryOperationLog)operationLog).Mode = OperationLogMode.Redo; } }
public override void OnActionSuccess(Context context) { using (TimedLock.Lock(_lock)) { if (_circuitState == CircuitState.HalfOpen) { OnCircuitReset(context); } _metrics.IncrementSuccess_NeedsLock(); } }
public new void RemoveWhere(Predicate <Entity> match) { using (TimedLock.Lock(_changeLock)) { foreach (var e in this.Where(match.Invoke)) { e.StatChanged -= _player.HandleStatChanges; } base.RemoveWhere(match); } }
/// <summary> /// Opens the store, preparing it for reading and writing messages and /// metadata to the backing store. /// </summary> public void Open() { using (TimedLock.Lock(this)) { if (this.messages != null) { throw new InvalidOperationException("Message store is already open."); } this.messages = new Dictionary <Guid, QueuedMsgInfo>(); } }
/// <summary> /// Transaction tekil değeri /// </summary> public string GetTransactionIdentifier() { using (TimedLock.Lock(this, new TimeSpan(0, 0, 6), string.Format("Basket=>{0}", this.GetType().Name)))//TODO: timeout süresini config'e al { if (string.IsNullOrEmpty(_transactionIdentifier)) { _transactionIdentifier = DateTime.Now.Ticks.ToString(); TransactionIdentifier = _transactionIdentifier; } return(_transactionIdentifier); } }
/// <summary> /// Queries the realm map provider for the current set of realm mappings. /// </summary> /// <returns>The list of realm mappings.</returns> /// <exception cref="AuthenticationException">Thrown if there's an error getting the map.</exception> public List <RealmMapping> GetMap() { using (TimedLock.Lock(this)) { if (!IsOpen) { throw new AuthenticationException("Provider is not open."); } return(LoadMap()); } }
public KeyVaultECDsaKeyStore( IAzureKeyVaultClients azureKeyVaultClients, IMemoryCache memoryCache, IOptions <KeyVaultStoreOptions> options, ILogger <KeyVaultECDsaKeyStore> logger) { _azureKeyVaultClients = azureKeyVaultClients; _memoryCache = memoryCache; _options = options.Value; _lock = new TimedLock(); _logger = logger; }
/// <summary> /// Broadcasts a message that commands all authentication client and service instances on the network /// to request a new authentication service public key before the next authentication /// attempt. /// </summary> /// <exception cref="AuthenticationException">Thrown if the authenticator is not open.</exception> public void BroadcastKeyUpdate() { using (TimedLock.Lock(this)) { if (!isOpen) { throw new AuthenticationException(NotOpenMsg); } router.BroadcastTo(AbstractAuthEP, new AuthControlMsg("auth-key-update", null)); } }
/// <summary> /// Returns an <see cref="IEnumerator" /> over the set of <see cref="QueuedMsgInfo" /> records describing /// each message currently persisted in the backing store. /// </summary> /// <returns>An <see cref="IEnumerator" /> instances.</returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { using (TimedLock.Lock(this)) { if (messages == null) { throw new ObjectDisposedException(this.GetType().Name); } return(messages.Values.GetEnumerator()); } }
/// <summary> /// Returns an <see cref="IEnumerator" /> over the set of <see cref="QueuedMsgInfo" /> records describing /// each message currently persisted in the backing store. /// </summary> /// <returns>An <see cref="IEnumerator" /> instances.</returns> IEnumerator <QueuedMsgInfo> IEnumerable <QueuedMsgInfo> .GetEnumerator() { using (TimedLock.Lock(this)) { if (messages == null) { throw new ObjectDisposedException(this.GetType().Name); } return(messages.Values.GetEnumerator()); } }
/// <summary> /// Reads the operation from the specified position in the log. /// </summary> /// <param name="resource">The parent <see cref="ITransactedResource" /> responsible for deserializing the operation.</param> /// <param name="position">See the <see cref="ILogPosition" />.</param> /// <returns>The <see cref="IOperation" /> read from the log.</returns> /// <exception cref="TransactionException">Thrown if the log is not open.</exception> public IOperation Read(ITransactedResource resource, ILogPosition position) { using (TimedLock.Lock(syncLock)) { if (!isOpen) { throw new TransactionException(NotOpenMsg); } return(operations[((MemoryLogPosition)position).Index]); } }
/// <summary> /// Called by derived classes when a new channel is created. /// </summary> /// <param name="channel">The new channel.</param> public virtual void AddChannel(LillTekChannelBase channel) { using (TimedLock.Lock(this)) { if (channels == null) { throw ServiceModelHelper.CreateObjectDisposedException(this); } channels.Add(channel.ID, (TInternal)channel); } }
/// <summary> /// Appends the operation to the end of the current transaction. /// </summary> /// <param name="operation">The <see cref="IOperation" /> to be appended.</param> /// <exception cref="TransactionException">Thrown if the stack is empty.</exception> public void Log(IOperation operation) { using (TimedLock.Lock(syncLock)) { if (base.Count == 0) { throw new TransactionException(EmptyMsg); } operationLog.Write(manager.Resource, operation); } }
//--------------------------------------------------------------------- // ILillTekChannelManager implementation /// <summary> /// Called by LillTek channels belonging to this channel manager when the /// channel is closed or aborted to terminate any pending operations. /// </summary> /// <param name="channel">The closed or aborted channel.</param> /// <param name="e">The exception to be used to terminate the operation.</param> public virtual void OnChannelCloseOrAbort(LillTekChannelBase channel, Exception e) { using (TimedLock.Lock(this)) { string channelID = channel.ID; if (channels.ContainsKey(channelID)) { channels.Remove(channelID); } } }
/// <summary> /// Appends an <see cref="IOperation" /> onto the end of the transaction's /// redo operation log. /// </summary> /// <param name="operation">The <see cref="IOperation" />.</param> /// <exception cref="TransactionException">Thrown if the transaction is not open.</exception> public void Log(IOperation operation) { using (TimedLock.Lock(syncLock)) { if (!isOpen) { throw new TransactionException(NotOpenMsg); } transBase.Log(operation); } }
public void method_8() { using (TimedLock.Lock(this.class65_0)) { TradeUser[] array = this.class65_0; for (int i = 0; i < array.Length; i++) { TradeUser @class = array[i]; @class.Boolean_0 = false; } } }
private void CreateFilteredList() { using (TimedLock.Lock(this, "CreatingFilteredList")) { visibleLines = new List <string>(); string[] allSourceLinesTemp = allSourceLines.ToArray(); foreach (string line in allSourceLinesTemp) { ConditionalyAddToVisible(line); } } }
/// <summary> /// Lock. /// </summary> /// <param name="o">o</param> /// <param name="timeout">Timeout.</param> /// <returns>Lock</returns> public static TimedLock Lock(object o, TimeSpan timeout) { TimedLock tl = new TimedLock(o); if (!Monitor.TryEnter(o, timeout)) { #if DEBUG System.GC.SuppressFinalize(tl); #endif throw new LockTimeoutException(); } return tl; }
public static TimedLock Lock(object o, TimeSpan timeout, string hint) { TimedLock tl = new TimedLock(o, hint); if (!Monitor.TryEnter(o, timeout)) { #if DEBUG System.GC.SuppressFinalize(tl); #endif string exceptionString = string.Format("Timeout waiting for lock: object type '{0}' content '{1}'", o.GetType().ToString(), o.ToString()); throw new LockTimeoutException(exceptionString); } return tl; }
/// <summary> /// Attempts to obtain a lock on the specified object for up to /// the specified timeout. /// </summary> /// <param name="o"></param> /// <param name="timeout"></param> /// <returns></returns> public static TimedLock Lock(object o, TimeSpan timeout) { Thread.BeginCriticalRegion(); var timedLock = new TimedLock(o); if (!Monitor.TryEnter(o, timeout)) { // Failed to acquire lock. #if DEBUG GC.SuppressFinalize(timedLock.leakDetector); throw new LockTimeoutException(o); #else throw new LockTimeoutException(); #endif } return timedLock; }