当前位置: 首页>>代码示例>>C#>>正文


C# ConcurrentDictionary.TryRemove方法代码示例

本文整理汇总了C#中ConcurrentDictionary.TryRemove方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentDictionary.TryRemove方法的具体用法?C# ConcurrentDictionary.TryRemove怎么用?C# ConcurrentDictionary.TryRemove使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ConcurrentDictionary的用法示例。


在下文中一共展示了ConcurrentDictionary.TryRemove方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Should_TryRemove_from_ConcurrentDictionary_using_comparison_value

        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);
        }
开发者ID:MarouenK,项目名称:Zebus,代码行数:11,代码来源:ExtendDictionaryTests.cs

示例2: Main

        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);
            }
        }
开发者ID:kenwilcox,项目名称:ConcurrentCollections,代码行数:31,代码来源:Program2.cs

示例3: ChannelFactory

        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);
        }
开发者ID:Originalutter,项目名称:RawRabbit,代码行数:35,代码来源:ChannelFactory.cs

示例4: Test_ConcurrentDictionary_04

 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);
     }
 }
开发者ID:labeuze,项目名称:source,代码行数:28,代码来源:Test_CollectionsConcurrent.cs

示例5: SimpleCache

 public SimpleCache(int maxNumberOfCacheEntries)
 {
     actualCache = new ConcurrentDictionary<string, CachedRequest>();
     lruKeys = new ConcurrentLruSet<string>(maxNumberOfCacheEntries, key =>
     {
         CachedRequest _;
         actualCache.TryRemove(key, out _);
     });
 }
开发者ID:j2jensen,项目名称:ravendb,代码行数:9,代码来源:SimpleCache.cs

示例6: Main

    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();
    }
开发者ID:MarkiyanMatsekh,项目名称:MultiplayerTetris,代码行数:56,代码来源:Program.cs

示例7: CreateBlock

    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;
    }
开发者ID:houcine,项目名称:statsd.net,代码行数:55,代码来源:TimedGaugeAggregatorBlockFactory.cs

示例8: ConcurrentDictionaryOps

        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);
            }
        }
开发者ID:Jac21,项目名称:GistsCollection,代码行数:48,代码来源:Program.cs

示例9: AverageOverTimeExceedsMax

 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;
 }
开发者ID:0liver,项目名称:DoS-Prevention,代码行数:18,代码来源:DosPreventionModule.cs

示例10: foreach

        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);
                }
            };
        }
开发者ID:Carbonitex,项目名称:Discord.Net,代码行数:18,代码来源:AudioService.cs

示例11: StartAsync

        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;
        }
开发者ID:dnauck,项目名称:async-dolls,代码行数:42,代码来源:DequeueStrategy.cs

示例12: EditWhileIterating

 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);
 }
开发者ID:mesheets,项目名称:Theraot-CF,代码行数:42,代码来源:ConcurrentDictionaryTestsEx.cs

示例13: MainWindowViewModel

        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();
        }
开发者ID:nagyist,项目名称:wpfrealtime,代码行数:41,代码来源:MainWindowViewModel.cs

示例14: TimedDurableCacheQueue

        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();
        }
开发者ID:Jarlotee,项目名称:xCache,代码行数:38,代码来源:TimedDurableCacheQueue.cs

示例15: AudioClient

		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);
				}
			};
		}
开发者ID:asdfgasdfsafgsdfa,项目名称:Discord.Net,代码行数:38,代码来源:AudioService.cs


注:本文中的ConcurrentDictionary.TryRemove方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。