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


C# ConcurrentDictionary.Where方法代码示例

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


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

示例1: HasDuplicateBranchReferences

        public static unsafe bool HasDuplicateBranchReferences(Transaction tx, Page start,out long pageNumberWithDuplicates)
        {
            var stack = new Stack<Page>();
            var existingTreeReferences = new ConcurrentDictionary<long, List<long>>();
            stack.Push(start);
            while (stack.Count > 0)
            {
                var currentPage = stack.Pop();
                if (currentPage.IsBranch)
                {
                    for (int nodeIndex = 0; nodeIndex < currentPage.NumberOfEntries; nodeIndex++)
                    {
                        var node = currentPage.GetNode(nodeIndex);

                        existingTreeReferences.AddOrUpdate(currentPage.PageNumber, new List<long> { node->PageNumber },
                            (branchPageNumber, pageNumberReferences) =>
                            {
                                pageNumberReferences.Add(node->PageNumber);
                                return pageNumberReferences;
                            });
                    }

                    for (int nodeIndex = 0; nodeIndex < currentPage.NumberOfEntries; nodeIndex++)
                    {
                        var node = currentPage.GetNode(nodeIndex);
                        if (node->PageNumber < 0 || node->PageNumber > tx.State.NextPageNumber)
                        {
                            throw new InvalidDataException("found invalid reference on branch - tree is corrupted");
                        }

                        var child = tx.GetReadOnlyPage(node->PageNumber);
                        stack.Push(child);
                    }

                }
            }

            Func<long, HashSet<long>> relevantPageReferences =
                branchPageNumber => new HashSet<long>(existingTreeReferences
                    .Where(kvp => kvp.Key != branchPageNumber)
                    .SelectMany(kvp => kvp.Value));

            // ReSharper disable once LoopCanBeConvertedToQuery
            foreach (var branchReferences in existingTreeReferences)
            {
                if (
                    branchReferences.Value.Any(
                        referencePageNumber => relevantPageReferences(branchReferences.Key).Contains(referencePageNumber)))
                {
                    pageNumberWithDuplicates = branchReferences.Key;
                    return true;
                }
            }
            pageNumberWithDuplicates = -1;
            return false;
        }
开发者ID:mattwarren,项目名称:LinqToMemory,代码行数:56,代码来源:DebugStuff.cs

示例2: WhenInboundHasProblemsOutboundJustKeepsOnTrucking

        public void WhenInboundHasProblemsOutboundJustKeepsOnTrucking(int numberOfMessages)
        {
            // arrange
            var receivedMessageCount = 0;
            var messageTracker = new ConcurrentDictionary<Guid, int>();
            var resetEvent = new ManualResetEvent(false);
            orderSystemHandlerActivator.Handle<PlaceOrderRequest>(req =>
                {
                    if (req.What != "beer" || req.HowMuch != 12) return;

                    OnCommit.Do(() =>
                        {
                            messageTracker.AddOrUpdate(req.MsgId, 1, (id, count) => count + 1);

                            var newValue = Interlocked.Increment(ref receivedMessageCount);
                            if (newValue >= numberOfMessages)
                            {
                                resetEvent.Set();
                            }
                        });
                });
            var timeout = numberOfMessages.Seconds();
            var keepMakingChaos = true;

            var chaosMonkey = new Thread(() =>
                {
                    while (keepMakingChaos)
                    {
                        Thread.Sleep(0.1.Seconds());
                        inbound.Stop();
                        Console.WriteLine("Inbound stopped - {0} messages processed...", receivedMessageCount);
                        Thread.Sleep(0.2.Seconds());
                        inbound.Start();
                        Thread.Sleep(2.2331.Seconds());
                    }
                });

            // act
            chaosMonkey.Start();
            numberOfMessages.Times(() => pricedesk.Send(CreateMessage()));

            // assert
            var resetEventWasSet = resetEvent.WaitOne(timeout + 5.Seconds());
            keepMakingChaos = false;
            chaosMonkey.Join();

            // chill, be more sure to empty the queue completely
            Thread.Sleep(1.Seconds());

            Assert.That(resetEventWasSet, Is.True, "Request was not received in order system within timeout of {0}", timeout);
            receivedMessageCount.ShouldBeGreaterThanOrEqualTo(numberOfMessages);
            Console.WriteLine("Actual number of received messages: {0}", receivedMessageCount);
            if (messageTracker.Any(t => t.Value > 1))
            {
                Console.WriteLine(@"The following IDs were received more than once:
            {0}", string.Join(Environment.NewLine, messageTracker.Where(t => t.Value > 1).Select(kvp => "    " + kvp.Key + ": " + kvp.Value)));
            }
            messageTracker.Count.ShouldBe(numberOfMessages);
        }
开发者ID:rasmuskl,项目名称:Rebus,代码行数:59,代码来源:TestGatewayIntegration.cs

示例3: GetGamesToFarmSolo

		private static HashSet<uint> GetGamesToFarmSolo(ConcurrentDictionary<uint, float> gamesToFarm) {
			if (gamesToFarm == null) {
				Logging.LogNullError(nameof(gamesToFarm));
				return null;
			}

			HashSet<uint> result = new HashSet<uint>();
			foreach (KeyValuePair<uint, float> keyValue in gamesToFarm.Where(keyValue => keyValue.Value >= 2)) {
				result.Add(keyValue.Key);
			}

			return result;
		}
开发者ID:xerohour,项目名称:ArchiSteamFarm,代码行数:13,代码来源:CardsFarmer.cs

示例4: Main

        public static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();

            List<Basket> baskets = new List<Basket>();
            ConcurrentDictionary<int, int> c1 = new ConcurrentDictionary<int, int>();
            for (int i = 0; i < NUM_BASKETS; i++)
            {
                var basket = ReadBasket("../../../../new_data/modified_basket_" + i.ToString("000000") + ".dat");
                baskets.Add(basket);
                foreach (var item in basket.Items)
                {
                    c1.AddOrUpdate(item.ItemId, 1, (key, value) => value + 1);
                }
            }
            var f1 = c1.Where(x => x.Value >= s).Select(x => x.Key).ToList();
            var c2 = new ConcurrentDictionary<Tuple<int, int>, int>();

            foreach (var basket in baskets)
            {
                for (int i = 0; i < basket.Items.Count - 1; i++)
                {
                    if (f1.Contains(basket.Items[i].ItemId))
                    {
                        for (int j = i + 1; j < basket.Items.Count; j++)
                        {
                            if (f1.Contains(basket.Items[j].ItemId))
                            {
                                c2.AddOrUpdate(new Tuple<int, int>(basket.Items[i].ItemId,
                                                                    basket.Items[j].ItemId),
                                                    1, (key, value) => value + 1);
                            }
                        }
                    }
                }
            }

            var f2 = c2.Where(x => x.Value >= s).ToList();

            /*
             * The pool of items that could be in a triple with support s consists of
             * items that are in at least two pairs with support s
             */
            var singleItems = new ConcurrentDictionary<int, int>();
            foreach (var pair in f2)
            {
                singleItems.AddOrUpdate(pair.Key.Item1, 1, (key, value) => value + 1);
                singleItems.AddOrUpdate(pair.Key.Item2, 1, (key, value) => value + 1);
            }
            var triplePool = singleItems.Keys.Where(x => x >= 2);

            var c3 = new ConcurrentDictionary<Tuple<int, int, int>, int>();
            foreach (var basket in baskets)
            {
                for (int i = 0; i < basket.Items.Count - 2; i++)
                {
                    if (triplePool.Contains(basket.Items[i].ItemId))
                    {
                        for (int j = i + 1; j < basket.Items.Count - 1; j++)
                        {
                            if (triplePool.Contains(basket.Items[j].ItemId))
                            {
                                for (int k = j + 1; k < basket.Items.Count; k++)
                                {
                                    if (triplePool.Contains(basket.Items[k].ItemId))
                                    {
                                        c3.AddOrUpdate(new Tuple<int, int, int>(basket.Items[i].ItemId,
                                                                                basket.Items[j].ItemId,
                                                                                basket.Items[k].ItemId),
                                                        1, (key, value) => value + 1);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            var f3 = c3.Where(x => x.Value >= s).ToList();

            using (var writer = new StreamWriter("../../../../output.txt"))
            {
                foreach (var itemSet in f3)
                {
                    writer.WriteLine(PrintSet(itemSet));
                }
            }

            // Stage 2
            Dictionary<string, int> sentiments = File.ReadLines("../../../../sentiment.csv")
                .Select(line => line.Split('\t'))
                .ToDictionary(line => line[0], line => Int32.Parse(line[1]));
            var triples = f3.Select(x => new Triple(x.Key.Item1, x.Key.Item2, x.Key.Item3)).ToList();

            foreach (var triple in triples)
            {
                foreach (var basket in baskets)
                {
                    var itemIds = basket.Items.Select(x => x.ItemId).ToList();
                    var day = GetDayOfWeek(basket.Weekday);
//.........这里部分代码省略.........
开发者ID:NathanDeMaria,项目名称:ScavengerHunt,代码行数:101,代码来源:Program.cs

示例5: DoWorkFrom

        private bool DoWorkFrom(
            ConcurrentDictionary<ITransferController, object> activeItems)
        {
            // Filter items with work only.
            List<KeyValuePair<ITransferController, object>> activeItemsWithWork =
                new List<KeyValuePair<ITransferController, object>>(
                    activeItems.Where(item => item.Key.HasWork && !item.Key.IsFinished));

            if (0 != activeItemsWithWork.Count)
            {
                // Select random item and get work delegate.
                int idx = this.randomGenerator.Next(activeItemsWithWork.Count);
                ITransferController transferController = activeItemsWithWork[idx].Key;

                DoControllerWork(transferController);

                return true;
            }

            return false;
        }
开发者ID:BeauGesteMark,项目名称:azure-storage-net-data-movement,代码行数:21,代码来源:TransferScheduler.cs

示例6: LotsOfAsyncStuffGoingDown

        public async Task LotsOfAsyncStuffGoingDown(int numberOfMessages)
        {
            var receivedMessages = 0;
            var messageIds = new ConcurrentDictionary<int, int>();

            Console.WriteLine("Sending {0} messages", numberOfMessages);

            await Task.WhenAll(Enumerable.Range(0, numberOfMessages)
                .Select(async i =>
                {
                    using (var context = new DefaultTransactionContext())
                    {
                        await _transport.Send(QueueName, RecognizableMessage(i), context);
                        await context.Complete();

                        messageIds[i] = 0;
                    }
                }));

            Console.WriteLine("Receiving {0} messages", numberOfMessages);

            using (var timer = new Timer(1000))
            {
                timer.Elapsed += delegate
                {
                    Console.WriteLine("Received: {0} msgs", receivedMessages);
                };
                timer.Start();

                await Task.WhenAll(Enumerable.Range(0, numberOfMessages)
                    .Select(async i =>
                    {
                        using (var context = new DefaultTransactionContext())
                        {
                            var msg = await _transport.Receive(context);
                            await context.Complete();

                            Interlocked.Increment(ref receivedMessages);

                            var id = int.Parse(msg.Headers["id"]);

                            messageIds.AddOrUpdate(id, 1, (_, existing) => existing + 1);
                        }
                    }));

                await Task.Delay(1000);
            }

            Assert.That(messageIds.Keys.OrderBy(k => k).ToArray(), Is.EqualTo(Enumerable.Range(0, numberOfMessages).ToArray()));

            var kvpsDifferentThanOne = messageIds.Where(kvp => kvp.Value != 1).ToList();

            if (kvpsDifferentThanOne.Any())
            {
                Assert.Fail(@"Oh no! the following IDs were not received exactly once:

{0}",
    string.Join(Environment.NewLine, kvpsDifferentThanOne.Select(kvp => string.Format("   {0}: {1}", kvp.Key, kvp.Value))));
            }
        }
开发者ID:ninocrudele,项目名称:Rebus,代码行数:60,代码来源:TestSqlServerTransport.cs

示例7: NizzleName

        public async Task NizzleName(int numberOfMessages, int numberOfWorkers)
        {
            var activator = new BuiltinHandlerActivator();
            var sentmessageIds = new ConcurrentDictionary<int, int>();
            var receivedMessageIds = new ConcurrentDictionary<int, int>();

            activator.Handle<SomeMessage>(async message =>
            {
                var id = message.Id;
                receivedMessageIds.AddOrUpdate(id, i => 1, (i, existing) => existing + 1);
            });

            var bus = (RebusBus)Configure.With(activator)
                .Logging(l => l.None())
                .Transport(t => t.UseMsmq(InputQueueName))
                .Routing(t => t.TypeBased().Map<SomeMessage>(InputQueueName))
                .Options(o => o.SetNumberOfWorkers(0))
                .Start();

            Using(bus);

            var sendStopwatch = Stopwatch.StartNew();

            Console.WriteLine("Sending {0} messages", numberOfMessages);

            await Task.WhenAll(Enumerable
                .Range(0, numberOfMessages)
                .Select(id => bus.Send(new SomeMessage { Id = id })));

            var elapsedSending = sendStopwatch.Elapsed;

            Console.WriteLine("SENT {0} messages in {1:0.0} s - that's {2:0.0}/s",
                numberOfMessages, elapsedSending.TotalSeconds, numberOfMessages / elapsedSending.TotalSeconds);

            bus.SetNumberOfWorkers(numberOfWorkers);

            var receiveStopwatch = Stopwatch.StartNew();
            Console.WriteLine("Waiting until they have been received");

            while (receivedMessageIds.Count < numberOfMessages)
            {
                Console.WriteLine("got {0} messages so far...", receivedMessageIds.Count);
                await Task.Delay(1000);
            }

            var elapsedReceiving = receiveStopwatch.Elapsed;

            Console.WriteLine("RECEIVED {0} messages in {1:0.0} s - that's {2:0.0}/s", 
                numberOfMessages, elapsedReceiving.TotalSeconds, numberOfMessages/elapsedReceiving.TotalSeconds);

            var sentButNotReceived = sentmessageIds.Keys.Except(receivedMessageIds.Keys).ToList();
            var receivedMoreThanOnce = receivedMessageIds.Where(kvp => kvp.Value > 1).ToList();

            if (sentButNotReceived.Any())
            {
                Assert.Fail("The following IDs were sent but not received: {0}", string.Join(", ", sentButNotReceived));
            }

            if (receivedMoreThanOnce.Any())
            {
                Assert.Fail("The following IDs were received more than once: {0}",
                    string.Join(", ", receivedMoreThanOnce.Select(kvp => string.Format("{0} ({1})", kvp.Key, kvp.Value))));
            }
        }
开发者ID:nls75,项目名称:Rebus,代码行数:64,代码来源:TestReceivePerformance.cs

示例8: GetQueuesOfImmatureSilos

 private static HashSet<QueueId> GetQueuesOfImmatureSilos(ISiloStatusOracle siloStatusOracle, 
     ConcurrentDictionary<SiloAddress, bool> immatureSilos, 
     Dictionary<string, List<QueueId>> idealDistribution)
 {
     HashSet<QueueId> queuesOfImmatureSilos = new HashSet<QueueId>();
     foreach (var silo in immatureSilos.Where(s => s.Value)) // take only those from immature set that have their immature status bit set
     {
         string siloName;
         if (siloStatusOracle.TryGetSiloName(silo.Key, out siloName))
         {
             List<QueueId> queues;
             if (idealDistribution.TryGetValue(siloName, out queues))
             {
                 queuesOfImmatureSilos.UnionWith(queues);
             }
         }
     }
     return queuesOfImmatureSilos;
 }
开发者ID:sbambach,项目名称:orleans,代码行数:19,代码来源:DeploymentBasedQueueBalancer.cs


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