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


C# ConcurrentBag.ToList方法代码示例

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


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

示例1: SendRequests

        private static void SendRequests(string baseAddress, int max)
        {
            foreach (var sleep in new[] { 1, 250, 500, 1000 }) {
                var tasks = new List<Task>();
                var responses = new ConcurrentBag<WebResponse>();
                var requestUrl = baseAddress + "home/index?sleep=" + sleep;
                Console.WriteLine("Requesting '{0}' {1} times...", requestUrl, max);
                var stopwatch = Stopwatch.StartNew();
                for (var i = 0; i < max; i++) {
                    tasks.Add(
                        Task.Factory.StartNew(() => responses.Add(
                            WebRequest.CreateDefault(
                                new Uri(requestUrl))
                                .GetResponse())));
                    Console.Write(".");
                }
                Task.WaitAll(tasks.ToArray());
                stopwatch.Stop();

                Console.WriteLine();
                Console.WriteLine("Requested '{0}' {1} times in {2}.", requestUrl, max, stopwatch.Elapsed.Duration());
                Console.WriteLine("First response:");
                var responseList = responses.ToList();
                WriteDebug(responseList[0]);
                var nr = max/2 - 1;
                Console.WriteLine("Response {0}:", nr);
                WriteDebug(responseList[nr]);
                nr = max - 1;
                Console.WriteLine("Response {0}:", nr);
                WriteDebug(responseList[nr]);
            }
        }
开发者ID:0liver,项目名称:DoS-Prevention,代码行数:32,代码来源:Program.cs

示例2: Compare

        /// <summary>
        /// </summary>
        /// <returns></returns>
        /// <exception cref="AggregateException">The exception that contains all the individual exceptions thrown on all threads.</exception>
        public List<FileInfo> Compare()
        {
            var listFromSetting = ConvertPathsFromSettingToDictionary();
            //var newer = new List<FileInfo>();
            var newer = new ConcurrentBag<FileInfo>();
            var listFromFileSystem = ListFromFileSystem();

            if (listFromSetting.Any() && listFromFileSystem.Any())
            {
                Parallel.ForEach(listFromFileSystem,
                    path =>
                    {
                        var file = new FileInfo(path);
                        if (listFromSetting.Any(item => item.Path == path))
                        {
                            var fromSetting = listFromSetting.First(list => list.Path == path);
                            if (File.Exists(fromSetting.Path) && fromSetting.LastWriteTime < file.LastWriteTime)
                            {
                                newer.Add(file);
                            }
                        }
                        else
                        {
                            newer.Add(file);
                        }
                    });
            }
            return newer.ToList();
        }
开发者ID:evilbaschdi,项目名称:FileWatcher,代码行数:33,代码来源:Worker.cs

示例3: GetExceptions

        public IList<Type> GetExceptions(Assembly assembly, IEnumerable<Type> exceptionsToIgnore)
        {
            Type typeOfException = typeof(Exception);
            ConcurrentBag<Type> types = new ConcurrentBag<Type>();

            Parallel.ForEach(
                assembly.GetTypes(),
                type =>
                {
                    if (exceptionsToIgnore != null && exceptionsToIgnore.Any())
                    {
                        if (exceptionsToIgnore.Contains(type))
                        {
                            return;
                        }
                    }

                    if (typeOfException.IsAssignableFrom(type))
                    {
                        types.Add(type);
                    }
                });

            return types.ToList();
        }
开发者ID:jeroenpot,项目名称:AutoTest.Exceptions,代码行数:25,代码来源:ExceptionResolver.cs

示例4: FindServers

        public Task<List<ServerDiscoveryInfo>> FindServers(int timeoutMs, CancellationToken cancellationToken = default(CancellationToken))
        {
            var taskCompletionSource = new TaskCompletionSource<List<ServerDiscoveryInfo>>();
            var serversFound = new ConcurrentBag<ServerDiscoveryInfo>();

            _logger.Debug("Searching for servers with timeout of {0} ms", timeoutMs);

            var innerCancellationSource = new CancellationTokenSource();
            var linkedCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(
                innerCancellationSource.Token, cancellationToken);

            BeginFindServers(serversFound, taskCompletionSource, innerCancellationSource);

            Task.Run(async () =>
            {
                try
                {
                    await Task.Delay(timeoutMs, linkedCancellationSource.Token).ConfigureAwait(false);
                    taskCompletionSource.TrySetResult(serversFound.ToList());
                }
                catch (OperationCanceledException)
                {
                    
                }
            });

            return taskCompletionSource.Task;
        }
开发者ID:daltekkie,项目名称:Emby.ApiClient,代码行数:28,代码来源:ServerLocator.cs

示例5: GetBuildInfoDtos

        public List<BuildInfoDto> GetBuildInfoDtos()
        {
            var buildInfoDtos = new ConcurrentBag<BuildInfoDto>();
            try
            {
                
                var tfsServer = _helperClass.GetTfsServer();
                // Get the catalog of team project collections
                var teamProjectCollectionNodes = tfsServer.CatalogNode.QueryChildren(
                    new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);
                var parallelOptions = new ParallelOptions {MaxDegreeOfParallelism = 1};
                Parallel.ForEach(teamProjectCollectionNodes, parallelOptions, teamProjectCollectionNode =>
                {
                    
                        var task = GetBuildInfoDtosPerTeamProject(teamProjectCollectionNode, tfsServer, DateTime.MinValue);
                        task.ConfigureAwait(false);
                        task.Wait();    
                        var buildInfos = task.Result;

                        foreach (var buildInfoDto in buildInfos)
                        {
                            buildInfoDtos.Add(buildInfoDto);
                        }
                        
                    
                });
            }
            catch (Exception e)
            {
                LogService.WriteError(e);
                throw;
            }

            return buildInfoDtos.ToList();
        }
开发者ID:ekkaj,项目名称:Buildscreen,代码行数:35,代码来源:TfsService.cs

示例6: GetGroupData

        public List<Group> GetGroupData(string databasePrefix, List<string> tableNames, DateTime beginTime, DateTime endTime, Dictionary<string, object> filters)
        {
            try
            {
                var data = new ConcurrentBag<Group>();
                var typeFullName = MongodbServerMaintainceCenter.GetTypeFullName(databasePrefix);
                var columnDescriptions = MongodbServerMaintainceCenter.GetMongodbColumnDescriptions(databasePrefix);
                var groupColumnDescriptions = columnDescriptions.Where(cd => cd.MongodbFilterOption == MongodbFilterOption.DropDownListFilter
                    || cd.MongodbFilterOption == MongodbFilterOption.CheckBoxListFilter || cd.MongodbCascadeFilterOption != MongodbCascadeFilterOption.None).ToList();

                var statTimeColumn = columnDescriptions.FirstOrDefault(c => c.IsTimeColumn);
                if (statTimeColumn == null) return data.ToList();
                var query = Query.LT(statTimeColumn.ColumnName, endTime).GTE(beginTime);


                Parallel.ForEach(tableNames, tableName =>
                {
                    var item = new Group();
                    item.GroupItems = new List<GroupItem>();
                    item.TableName = tableName;
                    groupColumnDescriptions.AsParallel().ForAll(groupColumnDescription =>
                    {
                        var groupItem = new GroupItem
                        {
                            Description = groupColumnDescription.Description,
                            DisplayName = groupColumnDescription.DisplayName,
                            Name = groupColumnDescription.ColumnName,
                            Values = new Dictionary<GroupItemValuePair, int>(),
                        };

                        groupItem.Values = InternalGetGroupData(typeFullName, databasePrefix, beginTime, endTime, tableName, query, groupColumnDescription.ColumnName, filters);
                        lock (item.GroupItems)
                            item.GroupItems.Add(groupItem);

                    });
                    data.Add(item);
                });
                return data.ToList();
            }
            catch (Exception ex)
            {
                LocalLoggingService.Error("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServer_Group", "GetGroupData", ex.Message);
                throw;
            }
        }
开发者ID:yhhno,项目名称:Adhesive,代码行数:45,代码来源:MongodbServer_Group.cs

示例7: CreateFingerprintsFromLogSpectrum

        private List<Fingerprint> CreateFingerprintsFromLogSpectrum(IEnumerable<SpectralImage> spectralImages, FingerprintConfiguration configuration)
        {
            var fingerprints = new ConcurrentBag<Fingerprint>();
            Parallel.ForEach(spectralImages, spectralImage =>
            {
                waveletDecomposition.DecomposeImageInPlace(spectralImage.Image);
                bool[] image = fingerprintDescriptor.ExtractTopWavelets(spectralImage.Image, configuration.TopWavelets);
                if (!IsSilence(image))
                {
                    fingerprints.Add(new Fingerprint(image, spectralImage.StartsAt, spectralImage.SequenceNumber));
                }
            });

            return fingerprints.ToList();
        }
开发者ID:AddictedCS,项目名称:soundfingerprinting,代码行数:15,代码来源:FingerprintService.cs

示例8: Search

		public SearchResult Search(SearchCriteria criteria)
		{
			SearchResult retVal = null;
			var cartIds = new List<string>();
			using (var repository = _repositoryFactory())
			{
				var query = repository.ShoppingCarts;
				if (criteria.CustomerId != null)
				{
					query = query.Where(x => x.CustomerId == criteria.CustomerId);
				}
				if (criteria.StoreId != null)
				{
					query = query.Where(x => x.StoreId == criteria.StoreId);
				}

				retVal = new SearchResult
				{
					TotalCount = query.Count(),

				};
				cartIds = query.OrderBy(x => x.CreatedDate)
										  .Skip(criteria.Start)
										  .Take(criteria.Count)
										  .Select(x => x.Id).ToList();

			}
			var carts = new ConcurrentBag<ShoppingCart>();
			var parallelOptions = new ParallelOptions
		   {
			   MaxDegreeOfParallelism = 10
		   };

			Parallel.ForEach(cartIds, parallelOptions, (x) =>
			{
				using (var repository = _repositoryFactory())
				{
					var cart = repository.GetShoppingCartById(x);
					carts.Add(cart.ToCoreModel());
				}
			});

			retVal.ShopingCarts = carts.ToList();
			return retVal;
		}
开发者ID:adwardliu,项目名称:vc-community,代码行数:45,代码来源:ShoppingCartSearchServiceImpl.cs

示例9: GetData

        public IEnumerable<dynamic> GetData()
        {
            var runners = new ConcurrentBag<ShadowRunner>();

            var availableOptions = options.Select(m => new List<char>
                                                       {
                                                           m
                                                       })
                                          .SelectMany(m => options.Except(m)
                                                                  .Select(a => new List<char>(m)
                                                                               {
                                                                                   a
                                                                               }))
                                          .SelectMany(m => options.Except(m)
                                                                  .Select(a => new List<char>(m)
                                                                               {
                                                                                   a
                                                                               }))
                                          .SelectMany(m => options.Except(m)
                                                                  .Select(a => new List<char>(m)
                                                                               {
                                                                                   a
                                                                               }))
                                          .SelectMany(m => options.Except(m)
                                                                  .Select(a => new List<char>(m)
                                                                               {
                                                                                   a
                                                                               }))
                                          .ToList();
            Parallel.ForEach(availableOptions,
                             choices =>
                             {
                                 var a = _runnerBuilder.Create(choices);
                                 foreach (var runner in a)
                                 {
                                     var score = _scorer.CalculateScore(runner);
                                     runner.Score = score;
                                     runners.Add(runner);
                                 }
                             });

            return runners.ToList()
                          .OrderByDescending(c => c.Score);
        }
开发者ID:GraemeBradbury,项目名称:GeneticRunner,代码行数:44,代码来源:Creator.cs

示例10: Main

        private static void Main(string[] args)
        {
            service = new DataService();
            liste = new ConcurrentBag<MusicInfo>();
            service.Clean();
            ProcessFolder(oriPath);
            Console.WriteLine(liste.Count);

            service.AddRange(liste.ToList());

            Console.ReadLine();

            foreach (var title in service.GetAll< MusicInfo>().Select(x => x.Title))
            {
                Console.WriteLine(title);
            }

            Console.ReadLine();
        }
开发者ID:Chapelin,项目名称:AuroraFooling,代码行数:19,代码来源:Program.cs

示例11: QueueStatus

 /// <summary>
 /// Initializes a new instance of the <see cref="QueueStatus"/> class.
 /// </summary>
 /// <param name="providers">The providers.</param>
 public QueueStatus(IEnumerable<IQueueStatusProvider> providers)
 {
     var statues = new ConcurrentBag<IQueueInformation>();
     Parallel.ForEach(providers, provider =>
     {
         IQueueInformation current;
         try
         {
             current = provider.Current;
         }
         catch (Exception error)
         {
             current = new QueueInformationError(provider.Name, provider.Server, error);
         }
         if (current != null)
         {
             statues.Add(current);
         }
     });
     Queues = statues.ToList();
 }
开发者ID:blehnen,项目名称:DotNetWorkQueue,代码行数:25,代码来源:QueueStatus.cs

示例12: Solve

        public IList<string> Solve(IAnagram anagram, string[] wordList, int maxWords)
        {
            if (maxWords == 0)
            {
                return new List<string>();
            }

            if (_dynamicMap.ContainsKey(anagram.ToString()))
            {
                return _dynamicMap[anagram.ToString()];
            }

            var containingWordList = wordList.Where(x => (anagram.ContainsWord(x))).ToArray();
            var solutions = new ConcurrentBag<string>();

            Parallel.For(0, containingWordList.Length - 1, i =>
            {
                var currentWord = containingWordList[i];
                var shorterAnagram = anagram.SubtractWord(currentWord);

                var solution = (shorterAnagram.Length == 0)
                    ? new List<string> {currentWord}
                    : ConcatList(currentWord,
                        Solve(shorterAnagram, containingWordList.Skip(i + 1).ToArray(), maxWords - 1));

                foreach (var s in solution)
                {
                    solutions.Add(s);
                }
            });

            var solutionsList = solutions.ToList();

            if (solutions.Count > 0)
            {
                _dynamicMap.TryAdd(anagram.ToString(), solutionsList);
            }

            return solutionsList;
        }
开发者ID:johnBartos,项目名称:AnagramChallenge,代码行数:40,代码来源:RecursiveAnagramFinder.cs

示例13: Inspect

            public List<ICodeInspectionResult> Inspect(RubberduckParserState state)
            {
                if (state == null || !state.AllUserDeclarations.Any())
                {
                    return new List<ICodeInspectionResult>();
                }

                state.OnStatusMessageUpdate(RubberduckUI.CodeInspections_Inspecting);

                var allIssues = new ConcurrentBag<ICodeInspectionResult>();

                // Prepare ParseTreeWalker based inspections
                var parseTreeWalkResults = GetParseTreeResults(state);
                foreach (var parseTreeInspection in _inspections.Where(inspection => inspection.Severity != CodeInspectionSeverity.DoNotShow && inspection is IParseTreeInspection))
                {
                    (parseTreeInspection as IParseTreeInspection).ParseTreeResults = parseTreeWalkResults;
                }

                var inspections = _inspections.Where(inspection => inspection.Severity != CodeInspectionSeverity.DoNotShow)
                    .Select(inspection =>
                        new Task(() =>
                        {
                            var inspectionResults = inspection.GetInspectionResults();
                            
                            foreach (var inspectionResult in inspectionResults)
                            {
                                allIssues.Add(inspectionResult);
                            }
                        })).ToArray();

                foreach (var inspection in inspections)
                {
                    inspection.Start();
                }

                Task.WaitAll(inspections);

                return allIssues.ToList();
            }
开发者ID:rubberduck-vba,项目名称:RubberduckWeb,代码行数:39,代码来源:DefaultInspector.cs

示例14: IndexFilesAsync

        public void IndexFilesAsync(FileInfo[] imageFiles, BackgroundWorker IndexBgWorker, object argument = null)
        {
            ConcurrentBag<PHashImageRecord> listOfRecords = new ConcurrentBag<PHashImageRecord>();

            string compressHash = string.Empty;
            int totalFileCount = imageFiles.Length;

            int i = 0; long nextSequence;
            //In the class scope: long nextSequence;
            Object lockMe = new Object();

            Parallel.ForEach(imageFiles, currentImageFile =>
            {
                var fi = currentImageFile;
                using (Bitmap bmp = new Bitmap(Image.FromFile(fi.FullName)))
                {
                    compressHash = SimilarImage.GetCompressedImageHashAsString(bmp);
                }

                lock (lockMe)
                {
                    nextSequence = i++;
                }

                PHashImageRecord record = new PHashImageRecord
                {
                    Id = nextSequence,
                    ImageName = fi.Name,
                    ImagePath = fi.FullName,
                    CompressHash = compressHash
                };

                listOfRecords.Add(record);

                IndexBgWorker.ReportProgress(i);
            });
            BinaryAlgoRepository<List<PHashImageRecord>> repo = new BinaryAlgoRepository<List<PHashImageRecord>>();
            repo.Save(listOfRecords.ToList());
        }
开发者ID:gjtjx,项目名称:ImageDatabase,代码行数:39,代码来源:pHashIndexer.cs

示例15: IndexFilesAsync

        public void IndexFilesAsync(FileInfo[] imageFiles, System.ComponentModel.BackgroundWorker IndexBgWorker, object argument = null)
        {
            ConcurrentBag<RGBProjectionRecord> listOfRecords = new ConcurrentBag<RGBProjectionRecord>();

            RgbProjections projections = null;
            int totalFileCount = imageFiles.Length;

            int i = 0; long nextSequence;
            //In the class scope:
            Object lockMe = new Object();

            Parallel.ForEach(imageFiles, currentImageFile =>
            {
                var fi = currentImageFile;
                using (Bitmap bitmap = ImageUtility.ResizeBitmap(new Bitmap(fi.FullName), 100, 100))
                {
                    projections = new RgbProjections(ImageUtility.GetRgbProjections(bitmap));
                }

                lock (lockMe)
                {
                    nextSequence = i++;
                }

                RGBProjectionRecord record = new RGBProjectionRecord
                {
                    Id = nextSequence,
                    ImageName = fi.Name,
                    ImagePath = fi.FullName,
                    RGBProjection = projections
                };

                listOfRecords.Add(record);

                IndexBgWorker.ReportProgress(i);
            });
            BinaryAlgoRepository<List<RGBProjectionRecord>> repo = new BinaryAlgoRepository<List<RGBProjectionRecord>>();
            repo.Save(listOfRecords.ToList());
        }
开发者ID:gjtjx,项目名称:ImageDatabase,代码行数:39,代码来源:RGBProjectionIndexer.cs


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