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


C# ConcurrentDictionary.ToArray方法代码示例

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


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

示例1: 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

示例2: CreateBlock

    public static ActionBlock<StatsdMessage> CreateBlock(ITargetBlock<Bucket> target,
      string rootNamespace, 
      IIntervalService intervalService,
      int percentile,
      string percentileName,
      ILog log,
      int maxItemsPerBucket = 1000)
    {
      var latencies = new ConcurrentDictionary<string, DatapointBox>();
      var root = rootNamespace;
      var ns = String.IsNullOrEmpty(rootNamespace) ? "" : rootNamespace + ".";
      var random = new Random();
      percentileName = "." + ( percentileName ?? ( "p" + percentile ) );

      var incoming = new ActionBlock<StatsdMessage>( p =>
        {
          var latency = p as Timing;
          latencies.AddOrUpdate(latency.Name,
              (key) =>
              {
                return new DatapointBox(maxItemsPerBucket, latency.ValueMS); 
              },
              (key, bag) =>
              {
                bag.Add(latency.ValueMS);
                return bag;
              });
        },
        new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded });

      intervalService.Elapsed += (sender, e) =>
        {
          if (latencies.Count == 0)
          {
            return;
          }
          var bucket = new PercentileBucket(latencies.ToArray(),
            e.Epoch,
            ns,
            percentileName,
            percentile);
          latencies.Clear();
          target.Post(bucket);
        };

      incoming.Completion.ContinueWith(p =>
        {
          // Tell the upstream block that we're done
          target.Complete();
        });
      return incoming;
    }
开发者ID:BookSwapSteve,项目名称:statsd.net,代码行数:52,代码来源:TimedLatencyPercentileAggregatorBlockFactory.cs

示例3: CreateBlock

    public static ActionBlock<StatsdMessage> CreateBlock(ITargetBlock<SetsBucket> target,
      string rootNamespace, 
      IIntervalService intervalService,
      ILog log)
    {
      var sets = new ConcurrentDictionary<string, ConcurrentDictionary<int, bool>>();
      var root = rootNamespace;
      var ns = String.IsNullOrEmpty(rootNamespace) ? "" : rootNamespace + ".";

      var incoming = new ActionBlock<StatsdMessage>(p =>
        {
          var set = p as Set;
          sets.AddOrUpdate(set.Name, 
            (key) =>
              {
                var setDict = new ConcurrentDictionary<int, bool>();
                setDict.AddOrUpdate( set.Value, ( key2 ) => true, ( key2, oldValue ) => true );
                return setDict;
              },
            (key, setDict) =>
              {
                setDict.AddOrUpdate( set.Value, ( key2 ) => true, ( key2, oldValue ) => true );
                return setDict;
              });
        },
        new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded });

      intervalService.Elapsed += (sender, e) =>
        {
          if (sets.Count == 0)
          {
            return;
          }
          var rawData = sets.ToArray();
          sets.Clear();
          var bucket = new SetsBucket(
            rawData.Select(p =>
              new KeyValuePair<string, List<KeyValuePair<int, bool>>>(p.Key, p.Value.ToList())
            ).ToList(),
            e.Epoch,
            ns);

          target.Post(bucket);
        };
      incoming.Completion.ContinueWith(p =>
        {
          // Tell the upstream block that we're done
          target.Complete();
        });
      return incoming;
    }
开发者ID:joshclark,项目名称:statsd.net,代码行数:51,代码来源:TimedSetAggregatorBlockFactory.cs

示例4: CreateBlock

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

      var incoming = new ActionBlock<StatsdMessage>(p =>
        {
          var counter = p as Counter;
          counters.AddOrUpdate(counter.Name, counter.Value, (key, oldValue) => oldValue + counter.Value);
        },
        new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded });

      intervalService.Elapsed += (sender, e) =>
        {
          if (counters.Count == 0)
          {
            return;
          }

          var bucket = new CounterBucket(counters.ToArray(), e.Epoch, ns);
          counters.Clear();
          target.Post(bucket);
        };

      incoming.Completion.ContinueWith(p =>
        {
          log.Info("TimedCounterAggregatorBlock completing.");
          // Tell the upstream block that we're done
          target.Complete();
        });
      return incoming;
    }
开发者ID:houcine,项目名称:statsd.net,代码行数:36,代码来源:TimedCounterAggregatorBlockFactory.cs

示例5: verify

        private void verify(ref ConcurrentDictionary<string, ConcurrentDictionary<string, long>> allresult)
        {
            // results should be sequential
            // ie S1 start S1 end before S1+n start and end

            foreach (var queuePair in allresult.ToArray())
            {
                var qName = queuePair.Key;
                var q = queuePair.Value; // value is ConcurrentDictionary<string, long>

                var qEntries = q.ToArray();
                var startEntries = qEntries.Where(  kvp => kvp.Key[0] == 'S' );

                // for each start task look for
                   // a task that started (between this start-end).
                    // a task that ended (between this start-end).
                // must not use Task sequence (as order) because tasks.
                // are placed in the actual queue based on priority.
                // slow stuff...
                foreach (var startEntry in startEntries)
                {
                    var TaskSeq = startEntry.Key.Substring(1, startEntry.Key.Length -1 );

                    var endEntry=
                        qEntries.SingleOrDefault(kvp => kvp.Key == string.Concat("E", TaskSeq));

                    var foundTask = qEntries.Where(
                                    kvp =>
                                    (
                                    // can use one comparison without key
                                    // but kept this way to be able to spit
                                    // out decent fail error if needed.
                                        kvp.Key[0] == 'S' &&
                                        kvp.Value > startEntry.Value &&
                                        kvp.Value < endEntry.Value
                                        ||
                                        kvp.Key[0] == 'E' &&
                                        kvp.Value > startEntry.Value &&
                                        kvp.Value < endEntry.Value
                                    )
                            );

                    if (0 != foundTask.Count())
                        Assert.Fail(string.Format("Q:{0} has a task started or ended while Task {1} was running",
                            qName, TaskSeq));
                }
            }
        }
开发者ID:khenidak,项目名称:WebSocketsServer,代码行数:48,代码来源:TaskScheduler.Tests.cs

示例6: CreateBlock

        public static ActionBlock<StatsdMessage> CreateBlock(ITargetBlock<CounterBucket> target,
          string rootNamespace,
          IIntervalService intervalService,
          ITimeWindowService timeWindowService,
          ILog log)
        {
            var windows = new ConcurrentDictionary<string, ConcurrentDictionary<string, double>>();
            var root = rootNamespace;
            var ns = String.IsNullOrEmpty(rootNamespace) ? "" : rootNamespace + ".";

            var incoming = new ActionBlock<StatsdMessage>(p =>
              {
                  var calendargram = p as Calendargram;
                  var metricName = calendargram.Name + METRIC_IDENTIFIER_SEPARATOR + calendargram.Value;

                  var period = timeWindowService.GetTimeWindow().GetTimePeriod(calendargram.Period);
                  windows.AddOrUpdate(period,
                    (key) =>
                    {
                        var window = new ConcurrentDictionary<string, double>();
                        window.AddOrUpdate(metricName, (key2) => 1, (key2, oldValue) => 1);
                        return window;
                    },
                    (key, window) =>
                    {
                        window.AddOrUpdate(metricName, (key2) => 1, (key2, oldValue) => 1);
                        return window;
                    }
                  );
              },
              new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded });

            intervalService.Elapsed += (sender, e) =>
              {
                  if (windows.Count == 0)
                  {
                      return;
                  }
                  var currentTimeWindow = timeWindowService.GetTimeWindow();

                  var periodsNotPresent = windows
                      .ToArray()
                      .Where(p => !currentTimeWindow.AllPeriods.Contains(p.Key))
                      .Select(p => p.Key);

                  CounterBucket bucket;

                  foreach (var period in periodsNotPresent)
                  {
                      ConcurrentDictionary<String, double> window;
                      if (windows.TryRemove(period, out window))
                      {
                          var parts = period.Split(UNDERSCORE);
                          var qualifier = "." + parts[0] + "." + parts[1];

                          var metricsAndValues = window.ToArray();
                          var metrics = new Dictionary<String, double>();
                          for (int index = 0; index < metricsAndValues.Length; index++)
                          {
                              var metricName = metricsAndValues[index].Key.Split(
                                  METRIC_IDENTIFIER_SEPARATOR_SPLITTER, 
                                  StringSplitOptions.RemoveEmptyEntries
                              )[0] + qualifier;

                              if (metrics.ContainsKey(metricName))
                              {
                                  metrics[metricName] += 1;
                              }
                              else
                              {
                                  metrics[metricName] = 1;
                              }
                          }

                          var metricList = metrics.Select(metric =>
                          {
                              return new KeyValuePair<string, double>(
                                metric.Key,
                                metric.Value
                              );
                          }).ToArray();
                          bucket = new CounterBucket(metricList, e.Epoch, ns);
                          target.Post(bucket);
                      }
                  }
              };
            incoming.Completion.ContinueWith(p =>
              {
                  log.Info("TimedCounterAggregatorBlock completing.");
                  // Tell the upstream block that we're done
                  target.Complete();
              });
            return incoming;
        }
开发者ID:houcine,项目名称:statsd.net,代码行数:94,代码来源:TimedCalendargramAggregatorBlockFactory.cs

示例7: TrimActiveActivityStore

        /// <summary>
        /// Normally this code never runs, it is here just to prevent run-away resource usage.  
        /// </summary>
        private static void TrimActiveActivityStore(ConcurrentDictionary<Guid, int> activities)
        {
            if (activities.Count > MaxActivityTrackCount)
            {
                // Remove half of the oldest activity ids.  
                var keyValues = activities.ToArray();
                var tickNow = Environment.TickCount;

                // Sort by age, taking into account wrap-around.   As long as x and y are within 
                // 23 days of now then (0x7FFFFFFF & (tickNow - x.Value)) is the delta (even if 
                // TickCount wraps).  I then sort by DESCENDING age.  (that is oldest value first)
                Array.Sort(keyValues, (x, y) => (0x7FFFFFFF & (tickNow - y.Value)) - (0x7FFFFFFF & (tickNow - x.Value)));
                for (int i = 0; i < keyValues.Length / 2; i++)
                {
                    int dummy;
                    activities.TryRemove(keyValues[i].Key, out dummy);
                }
            }
        }
开发者ID:REALTOBIZ,项目名称:mono,代码行数:22,代码来源:eventproviderbase.cs

示例8: RunDictionaryTest_Add1

        private static bool RunDictionaryTest_Add1(int cLevel, int initSize, int threads, int addsPerThread)
        {
            TestHarness.TestLog(
                "* RunDictionaryTest_Add1(cLevel={0}, initSize={1}, threads={2}, addsPerThread={3})",
                cLevel, initSize, threads, addsPerThread);

            IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);

            int count = threads;
            using (ManualResetEvent mre = new ManualResetEvent(false))
            {
                for (int i = 0; i < threads; i++)
                {
                    int ii = i;
                    ThreadPool.QueueUserWorkItem(
                        (o) =>
                        {
                            for (int j = 0; j < addsPerThread; j++)
                            {
                                dict.Add(j + ii * addsPerThread, -(j + ii * addsPerThread));
                            }
                            if (Interlocked.Decrement(ref count) == 0) mre.Set();
                        });
                }
                mre.WaitOne();
            }

            if (dict.Any(pair => pair.Key != -pair.Value))
            {
                TestHarness.TestLog("  > Invalid value for some key in the dictionary.");
                return false;
            }

            var gotKeys = dict.Select(pair => pair.Key).OrderBy(i => i).ToArray();
            var expectKeys = Enumerable.Range(0, threads * addsPerThread);

            if (!gotKeys.SequenceEqual(expectKeys))
            {
                TestHarness.TestLog("  > The set of keys in the dictionary is invalid.");
                return false;
            }

            // Finally, let's verify that the count is reported correctly.
            int expectedCount = threads * addsPerThread;
            if (dict.Count != expectedCount || dict.ToArray().Length != expectedCount || dict.ToList().Count() != expectedCount)
            {
                TestHarness.TestLog("  > Incorrect count of elements reported for the dictionary.");
                return false;
            }

            return true;
        }
开发者ID:modulexcite,项目名称:IL2JS,代码行数:52,代码来源:ConcurrentDictionaryTests.cs

示例9: RunDictionaryTest

        private static bool RunDictionaryTest(int cLevel, int initSize, int threads, int addsPerThread, TestMethod testMethod)
        {
            TestHarness.TestLog("* RunDictionaryTest_{0}, Level={1}, initSize={2}, threads={3}, addsPerThread={4})",
                            PrintTestMethod(testMethod), cLevel, initSize, threads, addsPerThread);

            ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);

            int count = threads;
            using (ManualResetEvent mre = new ManualResetEvent(false))
            {
                for (int i = 0; i < threads; i++)
                {
                    int ii = i;
                    ThreadPool.QueueUserWorkItem(
                        (o) =>
                        {
                            for (int j = 0; j < addsPerThread; j++)
                            {
                                //call either of the two overloads of GetOrAdd
                                if (j + ii % 2 == 0)
                                {
                                    dict.GetOrAdd(j, -j);
                                }
                                else
                                {
                                    dict.GetOrAdd(j, x => -x);
                                }
                            }
                            if (Interlocked.Decrement(ref count) == 0) mre.Set();
                        });
                }
                mre.WaitOne();
            }

            bool passed = true;

            if (dict.Any(pair => pair.Key != -pair.Value))
            {
                TestHarness.TestLog("  > Invalid value for some key in the dictionary.");
                passed = false;
            }


            var gotKeys = dict.Select(pair => pair.Key).OrderBy(i => i).ToArray();
            var expectKeys = Enumerable.Range(0, addsPerThread);

            if (!gotKeys.SequenceEqual(expectKeys))
            {
                TestHarness.TestLog("  > The set of keys in the dictionary is invalid.");
                passed = false;
            }

            // Finally, let's verify that the count is reported correctly.
            int expectedCount = addsPerThread;
            int count1 = dict.Count, count2 = dict.ToArray().Length,
                count3 = dict.ToList().Count;
            if (count1 != expectedCount || count2 != expectedCount || count3 != expectedCount)
            {
                TestHarness.TestLog("  > Incorrect count of elements reported for the dictionary. Expected {0}, Dict.Count {1}, ToArray.Length {2}, ToList.Count {3}",
                    expectedCount, count1, count2, count3);
                passed = false;
            }

            return passed;
        }
开发者ID:modulexcite,项目名称:IL2JS,代码行数:65,代码来源:ConcurrentDictionaryTests.cs

示例10: RunDictionaryTest_Remove3

        private static bool RunDictionaryTest_Remove3()
        {
            TestHarness.TestLog("* RunDictionaryTest_Remove3()");
            ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>();

            dict[99] = -99;

            ICollection<KeyValuePair<int, int>> col = dict;

            // Make sure we cannot "remove" a key/value pair which is not in the dictionary
            for (int i = 0; i < 1000; i++)
            {
                if (i != 99)
                {
                    if (col.Remove(new KeyValuePair<int, int>(i, -99)) || col.Remove(new KeyValuePair<int, int>(99, -i)))
                    {
                        TestHarness.TestLog("  > Removed a key/value pair which was not supposed to be in the dictionary.");
                        return false;
                    }
                }
            }

            // Can we remove a key/value pair successfully?
            if (!col.Remove(new KeyValuePair<int, int>(99, -99)))
            {
                TestHarness.TestLog("  > Failed to remove a key/value pair which was supposed to be in the dictionary.");
                return false;
            }

            // Make sure the key/value pair is gone
            if (col.Remove(new KeyValuePair<int, int>(99, -99)))
            {
                TestHarness.TestLog("  > Removed a key/value pair which was not supposed to be in the dictionary.");
                return false;
            }

            // And that the dictionary is empty. We will check the count in a few different ways:
            if (dict.Count != 0 || dict.ToArray().Count() != 0 || dict.ToList().Count() != 0)
            {
                TestHarness.TestLog("  > Incorrect count of elements reported for the dictionary.");
                return false;
            }

            return true;
        }
开发者ID:modulexcite,项目名称:IL2JS,代码行数:45,代码来源:ConcurrentDictionaryTests.cs

示例11: RunDictionaryTest_Remove1

        private static bool RunDictionaryTest_Remove1(int cLevel, int threads, int removesPerThread)
        {
            TestHarness.TestLog("* RunDictionaryTest_Remove1(cLevel={0}, threads={1}, removesPerThread={2})", cLevel, threads, removesPerThread);
            ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);

            int N = 2 * threads * removesPerThread;

            for (int i = 0; i < N; i++) dict[i] = -i;

            // The dictionary contains keys [0..N), each key mapped to a value equal to the key.
            // Threads will cooperatively remove all even keys.

            int running = threads;
            bool passed = true;

            using (ManualResetEvent mre = new ManualResetEvent(false))
            {
                for (int i = 0; i < threads; i++)
                {
                    int ii = i;
                    ThreadPool.QueueUserWorkItem(
                        (o) =>
                        {
                            for (int j = 0; j < removesPerThread; j++)
                            {
                                int value;
                                int key = 2 * (ii + j * threads);
                                if (!dict.TryRemove(key, out value))
                                {
                                    TestHarness.TestLog("  > Failed to remove an element, which should be in the dictionary.");
                                    passed = false;
                                    break;
                                }

                                if (value != -key)
                                {
                                    TestHarness.TestLog("  > Invalid value for some key in the dictionary.");
                                    passed = false;
                                    break;
                                }
                            }
                            if (Interlocked.Decrement(ref running) == 0) mre.Set();
                        });
                }
                mre.WaitOne();
            }

            if (!passed) return false;

            var res = dict.ToArray();
            if (res.Any(pair => pair.Key != -pair.Value))
            {
                TestHarness.TestLog("  > Invalid value for some key in the dictionary.");
                return false;
            }

            IEnumerable<int> gotKeys = res.Select(pair => pair.Key).OrderBy(i => i);
            IEnumerable<int> expectKeys = Enumerable.Range(0, threads * removesPerThread).Select(i => 2 * i + 1);
            if (!gotKeys.SequenceEqual(expectKeys))
            {
                TestHarness.TestLog("  > The set of keys in the dictionary is invalid.");
                return false;
            }

            // Finally, let's verify that the count is reported correctly.
            int expectedCount = expectKeys.Count();
            if (dict.Count != expectedCount || dict.ToArray().Length != expectedCount || dict.ToList().Count() != expectedCount)
            {
                TestHarness.TestLog("  > Incorrect count of elements reported for the dictionary.");
                return false;
            }

            return true;
        }
开发者ID:modulexcite,项目名称:IL2JS,代码行数:74,代码来源:ConcurrentDictionaryTests.cs

示例12: Given_different_thread_and_same_driver_environments_When_comparing_Then_should_not_be_equal

		public void Given_different_thread_and_same_driver_environments_When_comparing_Then_should_not_be_equal()
		{
			var sessions = new ConcurrentDictionary<Guid, Session>();

			Action action = () =>
			{
				var session = Threaded<Session>
					.With<PhantomJS>();
				sessions.TryAdd(Guid.NewGuid(), session);
			};

			var tasks = Enumerable
				.Repeat(0, 2)
				.Select(x => Task.Run(action));

			Task.WaitAll(tasks.ToArray());

			var session1 = sessions.ToArray()[0].Value;
			var session2 = sessions.ToArray()[1].Value;

			session1.Should().NotBe(session2);
			session1.Driver.Should().NotBeNull();
			session2.Driver.Should().NotBeNull();

			session1.End();
			session2.End();
		}
开发者ID:bumblebee,项目名称:bumblebee,代码行数:27,代码来源:ThreadedSessionTests.cs


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