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


C# ConcurrentBag.SelectMany方法代码示例

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


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

示例1: RunParallelForEach

        /// <summary>
        /// Use Parallel.ForEach
        /// </summary>
        private void RunParallelForEach()
        {
            var sw = Stopwatch.StartNew();
            var min = _fromDate.ToUniversalTime().Ticks;
            var max = _toDate.ToUniversalTime().Ticks;

            var table = _tableClient.GetTableReference("WADPerformanceCountersTable");

            var partition = Partitioner.Create(min, max + 1, (max - min)/_parallelism).GetDynamicPartitions();
            var resultBug = new ConcurrentBag<List<WADPerformanceCountersTable>>();

            Parallel.ForEach(partition,
                new ParallelOptions {MaxDegreeOfParallelism = _parallelism},
                () => new List<WADPerformanceCountersTable>(),
                (tuple, status, list) =>
                {
                    var resultRange = table.CreateQuery<WADPerformanceCountersTable>()
                        .Where(e =>
                            string.Compare(e.PartitionKey, tuple.Item1.ToString("d19"), StringComparison.Ordinal) >= 0 &&
                            string.Compare(e.PartitionKey, tuple.Item2.ToString("d19"), StringComparison.Ordinal) < 0)
                        .Select(e => e).ToArray();
                    if (_verbose > 0)
                        Console.WriteLine("{0},{1},{2},{3}", Thread.CurrentThread.ManagedThreadId, tuple.Item1, tuple.Item2, resultRange.Count());
                    list.AddRange(resultRange);
                    return list;
                },
                (list) => resultBug.Add(list));

            sw.Stop();

            var result = resultBug.SelectMany(list => list).ToArray();
            Console.WriteLine("Count:{0}, Min: {1}, Max: {2}, Elapsed: {3:F2} sec, PartitionKey:{4}",
                result.Count(), result.Min(e => e.PartitionKey), result.Max(e => e.PartitionKey), (sw.ElapsedMilliseconds / 1000.0), result.GroupBy(e => e.PartitionKey).Count());
        }
开发者ID:takekazuomi,项目名称:TableParallel,代码行数:37,代码来源:RunParallelForEach.cs

示例2: StartSimulation

        private async Task StartSimulation()
        {
            if(Simulator.SongData==null)
            {
                MessageBox.Show("楽曲を選んでください");
                return;
            }
            if (Simulator.Unit == null)
            {
                MessageBox.Show("ユニットを選んでください");
                return;
            }
            if (Runs < 1 || Runs > 1000000)
            {
                MessageBox.Show("試行回数は1から1,000,000までである必要があります");
                return;
            }

            Note[] pattern = null;
            if (UtilizeActualPattern)
            {
                pattern = await new PatternProvider().GetPattern(Simulator.Song, Simulator.SongData.Difficulty, Simulator.SongData.Notes);
                if (pattern == null)
                {
                    MessageBox.Show($"{Simulator.Song.Title}({Simulator.SongData.Difficulty})の譜面データが見つかりませんでした。");
                    return;
                }
            }

            SimulationCompleted = false;

            var results = new ConcurrentBag<SimulationResult>();
            await Task.Run(() => Parallel.For(1, Runs+1, i => results.Add(Simulator.StartSimulation(RandomFactory.Create(), i, pattern == null ? null : new Queue<Note>(pattern)))));

            MaxScore = results.Max(x=>x.Score);
            MaxScorePerNote = results.Max(x => x.ScorePerNote);

            MinScore = results.Min(x => x.Score);
            MinScorePerNote = results.Min(x => x.ScorePerNote);

            AverageScore = (int)results.Average(x => x.Score);
            AverageScorePerNote = (int)results.Average(x => x.ScorePerNote);

            ScoreDistribution = results.GroupBy(x => (int)Math.Floor(x.Score / 10000.0)).OrderBy(x => x.Key).ToDictionary(x => x.Key, x => (double)x.Count() / results.Count);

            StandardDeviation = Math.Round(Math.Sqrt(results.Sum(x => Math.Pow(x.Score - AverageScore, 2))) / results.Count);

            int idx = 1;
            var duration = results.First().Duration;
            ActualTriggerRatio = Simulator.Unit.Slots.ToDictionary(s => $"スロット{idx++}",
                s => s == null ? 0 : results.SelectMany(x => x.TriggeredSkills).Where(x => x.Who == s).Count() / (results.Count * Math.Floor((duration - 1.0) / s.Skill.Interval)));

            SimulationResults = results.OrderBy(x => x.Id).Take(100).ToList();
            SelectedResult = SimulationResults[0];

            SimulationCompleted = true;
        }
开发者ID:noelex,项目名称:Cindeck,代码行数:57,代码来源:SimulationViewModel.cs

示例3: UpdateAnimeGroupsAndTheirContracts

        private void UpdateAnimeGroupsAndTheirContracts(ISessionWrapper session, IReadOnlyCollection<AnimeGroup> groups)
        {
            _log.Info("Updating statistics and contracts for AnimeGroups");

            var allCreatedGroupUsers = new ConcurrentBag<List<AnimeGroup_User>>();

            // Update batches of AnimeGroup contracts in parallel. Each parallel branch requires it's own session since NHibernate sessions aren't thread safe.
            // The reason we're doing this in parallel is because updating contacts does a reasonable amount of work (including LZ4 compression)
            Parallel.ForEach(groups.Batch(DefaultBatchSize), new ParallelOptions { MaxDegreeOfParallelism = 4 },
                localInit: () => DatabaseFactory.SessionFactory.OpenStatelessSession(),
                body: (groupBatch, state, localSession) =>
                    {
                        var createdGroupUsers = new List<AnimeGroup_User>(groupBatch.Length);

                        // We shouldn't need to keep track of updates to AnimeGroup_Users in the below call, because they should have all been deleted,
                        // therefore they should all be new
                        AnimeGroup.BatchUpdateStats(groupBatch, watchedStats: true, missingEpsStats: true, createdGroupUsers: createdGroupUsers);
                        allCreatedGroupUsers.Add(createdGroupUsers);
                        AnimeGroup.BatchUpdateContracts(localSession.Wrap(), groupBatch, updateStats: true);

                        return localSession;
                    },
                localFinally: localSession => { localSession.Dispose(); });

            _animeGroupRepo.UpdateBatch(session, groups);
            _log.Info("AnimeGroup statistics and contracts have been updated");

            _log.Info("Creating AnimeGroup_Users and updating plex/kodi contracts");

            List<AnimeGroup_User> animeGroupUsers = allCreatedGroupUsers.SelectMany(groupUsers => groupUsers).ToList();

            // Insert the AnimeGroup_Users so that they get assigned a primary key before we update plex/kodi contracts
            _animeGroupUserRepo.InsertBatch(session, animeGroupUsers);
            // We need to repopulate caches for AnimeGroup_User and AnimeGroup because we've updated/inserted them
            // and they need to be up to date for the plex/kodi contract updating to work correctly
            _animeGroupUserRepo.Populate(session, displayname: false);
            _animeGroupRepo.Populate(session, displayname: false);

            // NOTE: There are situations in which UpdatePlexKodiContracts will cause database database writes to occur, so we can't
            // use Parallel.ForEach for the time being (If it was guaranteed to only read then we'd be ok)
            foreach (AnimeGroup_User groupUser in animeGroupUsers)
            {
                groupUser.UpdatePlexKodiContracts(session);
            }

            _animeGroupUserRepo.UpdateBatch(session, animeGroupUsers);
            _log.Info("AnimeGroup_Users have been created");
        }
开发者ID:ElementalCrisis,项目名称:jmmserver,代码行数:48,代码来源:AnimeGroupCreator.cs


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