Example #1
0
        public void CheckHandlersOnLoad()
        {
            var iter = _handlers.GetEnumerator();

            while (iter.MoveNext())
            {
                iter.Current.Value.FixWatchers();
            }
        }
Example #2
0
        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            var enc = clients.GetEnumerator();

            while (enc.MoveNext())
            {
                enc.Current.Value.socket.Close();
            }
            clients.Clear();
        }
Example #3
0
    public List <UnitController> getSelection()
    {
        List <UnitController> selection = new List <UnitController>();
        var enumerator = selectedTable.GetEnumerator();

        while (enumerator.MoveNext())
        {
            selection.Add(enumerator.Current.Value);
        }

        return(selection);
    }
Example #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="enumerator">返回False结束遍历</param>
        public void Foreach(Func <T, V, bool> enumerator)
        {
            var er = _cacheStruct.GetEnumerator();

            while (er.MoveNext())
            {
                if (!enumerator(er.Current.Key, er.Current.Value))
                {
                    break;
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="array"></param>
        /// <param name="arrayIndex"></param>
        public void CopyTo(KeyValuePair <string, object>[] array, int arrayIndex)
        {
            int index      = 0;
            var enumerator = _cacheStruct.GetEnumerator();

            while (enumerator.MoveNext())
            {
                if (index >= arrayIndex && index < array.Length)
                {
                    array[index] = enumerator.Current;
                }
                index++;
            }
        }
Example #6
0
        public IEnumerable <IAppSession> GetSessions(Predicate <IAppSession> critera = null)
        {
            var enumerator = _sessions.GetEnumerator();

            while (enumerator.MoveNext())
            {
                var s = enumerator.Current.Value;

                if (critera == null || critera(s))
                {
                    yield return(s);
                }
            }
        }
Example #7
0
        private void TimerElapsed(object state)
        {
            _logger.LogInformation("Timer elapsed");
            var actors = _actors.GetEnumerator();

            while (actors.MoveNext())
            {
                var loopTime = DateTime.UtcNow;
                var actor    = actors.Current.Value;
                if (actor != null && actor.IsActive)
                {
                    actor.TimerInterval(loopTime);
                }
            }
        }
Example #8
0
        /**
         * IClientToPM Methods
         */

        public void MetadataLocation(string id, string location)
        {
            Console.WriteLine("RECEIVED METADATA LOCATION " + location);

            IMetadataToClient metadata = (IMetadataToClient)Activator.GetObject(
                typeof(IMetadataToClient),
                location);

            metadatas[id]       = metadata;
            metadatasEnumerator = metadatas.GetEnumerator();

            // doesn't master who is the master now, just assign to it
            // when the first request is made, we will fix this
            master = id;
        }
Example #9
0
        public void SendToUdp(byte[] data, int offset, int size)
        {
            if (_targetPoint != null)
            {
                object[] state = new object[2];
                state[0] = size;
                state[1] = _targetPoint;

                UdpSocket.BeginSendTo(data, offset, size, SocketFlags.None, _targetPoint, new AsyncCallback(
                                          OnUdpWriteComplete), state);
                return;
            }

            var enu = _clients.GetEnumerator();

            while (enu.MoveNext())
            {
                object[] state = new object[2];
                state[0] = size;
                state[1] = enu.Current.Key;

                UdpSocket.BeginSendTo(data, offset, size, SocketFlags.None, enu.Current.Key, new AsyncCallback(
                                          OnUdpWriteComplete), state);
            }
        }
Example #10
0
        internal static void RegisterAllConnections()
        {
            ConcurrentDictionary <string, bool> dbproviderRegistereds = new ConcurrentDictionary <string, bool>();
            IEnumerator <KeyValuePair <string, ConnectionSetting> > e = sConnectionSettings.GetEnumerator();

            while (e.MoveNext())
            {
                ConnectionSetting conn    = e.Current.Value;
                string            dialect = conn.Dialect.ToLower();
                if (!dbproviderRegistereds.ContainsKey(dialect))
                {
                    if (sAllowedDatabases.ContainsKey(dialect))
                    {
                        DbUtils.RegisterDbProvider(dialect, sAllowedDatabases[dialect]);
                        dbproviderRegistereds.TryAdd(dialect, true);
                    }
                    else
                    {
                        throw new Exception(string.Concat("不支持的数据库:", conn.Dialect));
                    }
                }

                DbUtils.AddDataSource(conn.DataSource, dialect, conn.ToString());
            }
        }
Example #11
0
        private int GetNextTickId()
        {
            using (var enumerator = Ticks.GetEnumerator())
            {
                if (!enumerator.MoveNext())
                {
                    return(0);
                }

                var nextKeyInSequence = enumerator.Current.Key + 1;

                if (nextKeyInSequence < 1)
                {
                    throw new InvalidOperationException("The dictionary contains keys less than 0");
                }

                if (nextKeyInSequence != 1)
                {
                    return(0);
                }

                while (enumerator.MoveNext())
                {
                    var key = enumerator.Current.Key;
                    if (key > nextKeyInSequence)
                    {
                        return(nextKeyInSequence);
                    }

                    ++nextKeyInSequence;
                }

                return(nextKeyInSequence);
            }
        }
Example #12
0
        public ChannelFactory(RawRabbitConfiguration config, IConnectionFactory connectionFactory)
        {
            _connectionFactory = connectionFactory;
            _accessDictionary = new ConcurrentDictionary<IModel, DateTime>();
            _config = config;
            _threadChannels = new ThreadLocal<IModel>(true);

            try
            {
                _logger.LogDebug("Connecting to primary host.");
                _connection = _connectionFactory.CreateConnection(_config.Hostnames);
                _logger.LogInformation("Successfully established connection.");
            }
            catch (BrokerUnreachableException e)
            {
                _logger.LogError("Unable to connect to broker", e);
                throw e.InnerException;
            }
            _closeTimer = new System.Threading.Timer(state =>
            {
                var enumerator = _accessDictionary.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    if (DateTime.Now - enumerator.Current.Value > _config.RequestTimeout)
                    {
                        DateTime lastUsed;
                        if (_accessDictionary.TryRemove(enumerator.Current.Key, out lastUsed))
                        {
                            _logger.LogInformation($"Channel {enumerator.Current.Key.ChannelNumber} was last used {lastUsed}. Closing...");
                            enumerator.Current.Key.Close();
                        }
                    }
                }
            }, null, _config.RequestTimeout, _config.RequestTimeout);
        }
        public ThreadBasedChannelFactory(RawRabbitConfiguration config, IConnectionFactory connectionFactory)
        {
            _connectionFactory = connectionFactory;
            _accessDictionary  = new ConcurrentDictionary <IModel, DateTime>();
            _config            = config;
            _threadChannels    = new ThreadLocal <IModel>(true);

            try
            {
                _logger.LogDebug("Connecting to primary host.");
                _connection = _connectionFactory.CreateConnection(_config.Hostnames);
                _logger.LogInformation("Successfully established connection.");
            }
            catch (BrokerUnreachableException e)
            {
                _logger.LogError("Unable to connect to broker", e);
                throw e.InnerException;
            }
            _closeTimer = new System.Threading.Timer(state =>
            {
                var enumerator = _accessDictionary.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    if (DateTime.Now - enumerator.Current.Value > _config.RequestTimeout)
                    {
                        DateTime lastUsed;
                        if (_accessDictionary.TryRemove(enumerator.Current.Key, out lastUsed))
                        {
                            _logger.LogInformation($"Channel {enumerator.Current.Key.ChannelNumber} was last used {lastUsed}. Closing...");
                            enumerator.Current.Key.Close();
                        }
                    }
                }
            }, null, _config.RequestTimeout, _config.RequestTimeout);
        }
 public CookieJarEnumerator(
     ConcurrentDictionary <string, ConcurrentDictionary <string, Cookie> > store,
     ConcurrentDictionary <string, ConcurrentDictionary <string, Cookie> > secureStore)
 {
     _enumerator       = store.GetEnumerator();
     _secureEnumerator = secureStore.GetEnumerator();
 }
Example #15
0
        private static void ExpireCache()
        {
            if (_needsReset)
            {
                if (Environment.TickCount - _lastCacheEnumeratorResetTime < CacheIterationInterval)
                {
                    return;
                }
                _lastCacheEnumeratorResetTime = Environment.TickCount;
                _expirationEnumerator         = _cache.GetEnumerator();
                _needsReset = false;
            }

            if (_expirationEnumerator.MoveNext())
            {
                var entry = _expirationEnumerator.Current;
                if (entry.Value.Expired)
                {
                    Remove(entry.Key);
                }
            }
            else
            {
                _needsReset = true;
            }
        }
Example #16
0
        private void StartSessionWatcher(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;

            while (worker.CancellationPending == false)
            {
                Thread.Sleep(CHECK_INTERVAL);
                try {
                    var enumerator = _sessionsList.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        try {
                            var session = enumerator.Current.Value;
                            if (!session.IsAlive)
                            {
                                LogOut(session);
                            }
                        } catch (Exception ex) {
                            var message = string.Format("Session watcher error: can get current session state or logout. Session: {0}", enumerator.Current.Value);
                            Logger.AddError(message);
                        }
                    }
                } catch (Exception ex) {
                    var message = string.Format("Session watcher error: can get sessions enumerator or moveNext. Session list: {0}", string.Join(" ;", _sessionsList));
                    Logger.AddError(message);
                }
            }
        }
 public void Dispose()
 {
     if (_typeActivatorCache != null && _typeActivatorCache.Count > 0)
     {
         _typeActivatorCache.GetEnumerator().Dispose();
     }
 }
Example #18
0
 /**
  * Stops all threads created by <I>all</I> <TT>CSPParallel</TT> and {@link ProcessManager} objects. No new threads can be
  * created until the <TT>resetDestroy</TT> method gets called.
  */
 public static void destroy()
 {
     lock (allParThreads)
     {
         if (!destroyCalled)
         {
             Console.WriteLine("*** jcsp.lang.CSPParallel: stopping " +
                               allParThreads.Count + " threads");
             //allParThreads.Size() + " threads");
             for (var i = allParThreads.GetEnumerator(); i.MoveNext();)
             {
                 /*final*/
                 ParThread t = i.Current.Value;
                 try
                 {
                     t.Interrupt();
                 }
                 catch (SecurityException e)
                 {
                     Console.WriteLine("*** jcsp.lang.CSPParallel: couldn't stop thread " +
                                       t + " - security exception");
                 }
             }
             destroyCalled = true;
         }
     }
 }
Example #19
0
 public IEnumerator <KeyValuePair <TKey, TValue> > GetEnumerator()
 {
     if (dict == null)
     {
         return(Enumerable.Empty <KeyValuePair <TKey, TValue> >().GetEnumerator());
     }
     return(dict.GetEnumerator());
 }
        public void GetEnumerator_ThrowsNotImplementedException()
        {
            // Arrange
            ConcurrentDictionary <int, int> dictionary = new ConcurrentDictionary <int, int>();

            // Act/Assert
            Assert.Throws <NotImplementedException>(() => dictionary.GetEnumerator());
        }
Example #21
0
        // can't be in loop since we know for sure 1 metadata is up
        private void RandomMaster()
        {
            while (true)
            {
                if (!metadatasEnumerator.MoveNext())
                {
                    metadatasEnumerator = metadatas.GetEnumerator();
                    continue;
                }

                if (master != metadatasEnumerator.Current.Key)
                {
                    master = metadatasEnumerator.Current.Key;
                    return;
                }
            }
        }
Example #22
0
        private void TimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
        {
            //send anything left in the queue
            if (EffectiveWindow > 0 && sendQueue.Count > 0)
            {
                int toSend = sendQueue.Count - EffectiveWindow;
                while (EffectiveWindow > 0 && toSend > 0)
                {
                    TimestampedPacket timestampedPacket;
                    if (this.sendQueue.TryDequeue(out timestampedPacket))
                    {
                        this.SendTimestampedPacket(timestampedPacket);
                    }
                }
            }

            //search over the ackqueue and look for anything that is over the transmission timeout to retransmit
            var enumerator = acks.GetEnumerator();

            while (enumerator.MoveNext())
            {
                TimestampedPacket tsp = enumerator.Current.Value;
                int tick = Environment.TickCount - tsp.lastTransmissionTime;

                if (tick >= RetransmitInterval)
                {
                    Console.WriteLine(String.Format("Resending packet Seq#:{0}", tsp.packet.Seq));
                    this.packetSender.SendPacket(tsp.packet);
                    tsp.lastTransmissionTime = Environment.TickCount;
                    tsp.retransmissionCount++;
                    if (tsp.retransmissionCount > this.RetransmitInterval)
                    {
                        tsp.timedOut = true;
                        this.PacketDropped(tsp.retransmissionCount, tsp.lastTransmissionTime);
                    }
                }
            }

            /*for (uint i = 0; i < acks.Count; i++)
             * {
             *                  Console.WriteLine ("Resending");
             *                  TimestampedPacket tsp = acks.GetEnumerator ().
             *                  int tick = Environment.TickCount - tsp.lastTransmissionTime;
             *
             *                  if ( tick >= RetransmitInterval)
             *  {
             *      Console.WriteLine(String.Format("Resending packet Seq#:{0}", tsp.packet.Seq));
             *      this.packetSender.SendPacket(tsp.packet);
             *      tsp.lastTransmissionTime = Environment.TickCount;
             *      tsp.retransmissionCount++;
             *      if (tsp.retransmissionCount > this.RetransmitInterval)
             *      {
             *          tsp.timedOut = true;
             *          this.PacketDropped(tsp.retransmissionCount, tsp.lastTransmissionTime);
             *      }
             *  }
             * }*/
        }
        public void Close()
        {
            lock (_InitializationLock)
            {
                try
                {
                    if (null != _Socket)
                    {
                        _Socket.Close();
                        _Socket = null;
                    }

                    if (null != _IncomingStreamHandler)
                    {
                        _IncomingStreamHandler.Stop();
                        _IncomingStreamHandler = null;
                    }

                    if (null != _OutgoingStreamHandler)
                    {
                        _OutgoingStreamHandler.Stop();
                        _OutgoingStreamHandler = null;
                    }

                    //notify connection change
                    if (null != _ConnectionListener)
                    {
                        _ConnectionListener.OnGazeApiConnectionStateChanged(false);
                    }

                    //We cancel queued requests
                    if (null != _RequestQueue)
                    {
                        CancelAllRequests();
                        _RequestQueue.Stop();
                    }
                    _RequestQueue = null;

                    //We make sure we cancel currently ongoing requests
                    if (null != _OngoingRequests)
                    {
                        IEnumerator <KeyValuePair <int, IRequest> > reqs = _OngoingRequests.GetEnumerator();

                        while (reqs.MoveNext())
                        {
                            reqs.Current.Value.Cancel();
                        }
                        _OngoingRequests.Clear();
                    }
                    _OngoingRequests = null;
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Error closing socket: " + e.Message);
                }
            }
        }
        public void Update(double elapsed)
        {
            if (elapsed > ServerConfig.FrameSpendMaxTime)
            {
                DebugSystem.LogError("帧 时间 太长: " + elapsed);
            }

            lock (mClientDic) {
                if (!mClientDic.IsEmpty)
                {
                    var iter = mClientDic.GetEnumerator();
                    while (iter.MoveNext())
                    {
                        iter.Current.Value.Update(elapsed);
                    }
                }
            }
        }
        public IEnumerable <IAppSession> GetSessions(Predicate <IAppSession> criteria = null)
        {
            var enumerator = _sessions.GetEnumerator();

            while (enumerator.MoveNext())
            {
                var s = enumerator.Current.Value;

                if (s.State != SessionState.Connected)
                {
                    continue;
                }

                if (criteria == null || criteria(s))
                {
                    yield return(s);
                }
            }
        }
Example #26
0
        /// <summary>
        /// Called from setter of VirtualURLLifeSpan. Changes the time span of all the objects associated with the Url.
        /// Warning : It will refresh the timeout from DateTime.Now.
        /// </summary>
        public void UpdateTimeOutOfAllUrls()
        {
            IEnumerator <KeyValuePair <string, HttpResponseBuffer> > enumerator = _httpUrlList.GetEnumerator();

            while (enumerator.MoveNext())
            {
                KeyValuePair <string, HttpResponseBuffer> value = enumerator.Current;
                value.Value.UpdateTimeOut();
            }
        }
Example #27
0
        /// <summary>
        /// Trys to remove a player
        /// </summary>
        /// <param name="username">The player's username</param>
        /// <returns>True if removed; otherwise false</returns>
        public bool Remove(string username)
        {
            using (IEnumerator <KeyValuePair <int, WorldPlayer> > enumerator = m_Players.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    if (enumerator.Current.Value.IsConnectedPlayer)
                    {
                        continue;
                    }

                    if (string.Compare(enumerator.Current.Value.Username, username, true) == 0)
                    {
                        return(this.Remove(enumerator.Current.Key));
                    }
                }
            }

            return(false);
        }
Example #28
0
 /// <summary>
 /// Shortcut to thread safe enumeration of Concurrent Dictionaries
 /// </summary>
 /// <typeparam name="TKey"></typeparam>
 /// <typeparam name="TVal"></typeparam>
 /// <param name="collection"></param>
 /// <param name="action"></param>
 public static void ForeachConcurrent <TKey, TVal>(
     this ConcurrentDictionary <TKey, TVal> collection,
     Action <TKey, TVal> action)
 {
     using (var enumerator = collection.GetEnumerator())
     {
         while (enumerator.MoveNext())
         {
             action(enumerator.Current.Key, enumerator.Current.Value);
         }
     }
 }
Example #29
0
 internal void WaitForAllPendingActions(int timeoutMs)
 {
     while (_startedActons.Count > 0)
     {
         var it = _startedActons.GetEnumerator();
         it.MoveNext();
         var ar = it.Current.Value as AsyncResultNoResult;
         ar.AsyncWaitHandle.WaitOne(timeoutMs);
         IAsyncResult oar;
         _startedActons.TryRemove(ar.Id, out oar);
     }
 }
Example #30
0
        public static void RemoveByPattern(string pattern)
        {
            var   enumerator = cache.GetEnumerator();
            Regex regex      = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);

            while (enumerator.MoveNext())
            {
                string input = enumerator.Current.Key.ToString();
                if (regex.IsMatch(input))
                {
                    Remove(input);
                }
            }
        }
Example #31
0
        public static void RemoveByPattern(string pattern)
        {
            // ReSharper disable once GenericEnumeratorNotDisposed
            var enumerator = Cache.GetEnumerator();
            var regex      = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);

            while (enumerator.MoveNext())
            {
                var input = enumerator.Current.Key;
                if (regex.IsMatch(input))
                {
                    Remove(input);
                }
            }
        }
        public void GetEnumerator_ThrowsNotImplementedException()
        {
            // Arrange
            ConcurrentDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();

            // Act/Assert
            Assert.Throws<NotImplementedException>(() => dictionary.GetEnumerator());
        }