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


C# ConcurrentBag.Where方法代码示例

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


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

示例1: GetIssues

        public IEnumerable<CodeIssue> GetIssues(IDocument document, CommonSyntaxNode node, CancellationToken cancellationToken)
        {
            var identifiers = GetIdentifiers(node);

            foreach (var identifier in identifiers)
            {
                var words = camelCaseSplit(identifier.ValueText)
                            .Where(w => AlphaLongerThanTwoCharacters.IsMatch(w));

                var allIssues = new ConcurrentBag<SpellingIssue>();
                var result = Parallel.ForEach(words,
                    () => (SpellingIssue)null,
                    (word, state, dummy) => IdentifyIssues(word, document, identifier, node, state, dummy),
                    issue => allIssues.Add(issue));

                foreach (var spellingIssue in allIssues.Where(i => i != null))
                {
                    yield return new CodeIssue(CodeIssueKind.Warning, spellingIssue.Span,
                                               string.Format("Possible mis-spelling: {0}", spellingIssue.Word),
                                               spellingIssue.Actions);
                }
            }
        }
开发者ID:PashaPash,项目名称:Refactorings,代码行数:23,代码来源:SpellingCodeIssueProvider.cs

示例2: FindSolutions

        public Solution[] FindSolutions(Solution previousSolution)
        {
            var solutions = new ConcurrentBag<Solution>();

            for (int i = 0; i < 64; i++)
            {
                int x = i%8;
                int y = i/8;

                BoardPosition position = originalBoard[y, x];
                solutions.Add(MoveRightSolves(position));
                solutions.Add(MoveDownSolves(position));
                solutions.Add(MoveLeftSolves(position));
                solutions.Add(MoveUpSolves(position));
            };

            var orderedSolutions = solutions
                .Where(m => m.Weight > 1)
                .Select(this.ApplySolutionLocationWeight)
                .Select(s => this.ApplyDistanceFromPreviousSolutionWeight(s, previousSolution))
                .OrderByDescending(s => s.Weight);

            return orderedSolutions.ToArray();
        }
开发者ID:jweber,项目名称:bbplayer,代码行数:24,代码来源:SolutionFinder.cs

示例3: Run

        public static async Task Run(List<RunDescriptor> runDescriptors, List<EndpointBehavior> behaviorDescriptors, List<IScenarioVerification> shoulds, Func<ScenarioContext, bool> done, Action<RunSummary> reports)
        {
            var totalRuns = runDescriptors.Count;

            var results = new ConcurrentBag<RunSummary>();

            try
            {
                foreach (var runDescriptor in runDescriptors)
                {
                    Console.WriteLine("{0} - Started @ {1}", runDescriptor.Key, DateTime.Now.ToString(CultureInfo.InvariantCulture));

                    ContextAppenderFactory.SetContext(runDescriptor.ScenarioContext);
                    var runResult = await PerformTestRun(behaviorDescriptors, shoulds, runDescriptor, done).ConfigureAwait(false);
                    ContextAppenderFactory.SetContext(null);

                    Console.WriteLine("{0} - Finished @ {1}", runDescriptor.Key, DateTime.Now.ToString(CultureInfo.InvariantCulture));

                    results.Add(new RunSummary
                    {
                        Result = runResult,
                        RunDescriptor = runDescriptor,
                        Endpoints = behaviorDescriptors
                    });

                    if (runResult.Failed)
                    {
                        break;
                    }
                }
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine("Test run aborted due to test failures");
            }

            var failedRuns = results.Where(s => s.Result.Failed).ToList();

            foreach (var runSummary in failedRuns)
            {
                DisplayRunResult(runSummary, totalRuns);
            }

            if (failedRuns.Count == 1)
            {
                throw failedRuns[0].Result.Exception;
            }

            if (failedRuns.Count > 1)
            {
                throw new AggregateException("Test run failed due to multiple exceptions", failedRuns.Select(f => f.Result.Exception)).Flatten();
            }

            foreach (var runSummary in results.Where(s => !s.Result.Failed))
            {
                DisplayRunResult(runSummary, totalRuns);

                reports?.Invoke(runSummary);
            }
        }
开发者ID:Particular,项目名称:NServiceBus,代码行数:60,代码来源:ScenarioRunner.cs

示例4: GetYoungestCustomersAsync

        /// <summary>
        /// Gets the youngest customers with valid phone numbers
        /// </summary>
        /// <param name="count"> customer count</param>
        /// <returns>List of youngest 'count' number of customers with valid phone numbers sorted by their name </returns>
        public async Task<List<Customer>> GetYoungestCustomersAsync(int count)
        {
            if (count <= 0)
            {
                throw new ArgumentException(string.Format("'count' must be greater than 0. Actual value is {0}", count));
            }

            UserIdListData content = await this.customerDataClient.GetUserListAsync(null);
            
            List<int> userIds = new List<int>();
            userIds.AddRange(content.Result);
            
            // In this approach we are getting all the user ids sequentially and then retrieving the user details in parallel
            // The assumption here is that the size of the data here is less since we are only retrieving the ids, hence the calls will be faster
            // If there are too many users, we could start querying the userDetails in parallel, without waiting to retrieve
            // all the user ids.
            while (content.Token != null)
            {
                content = await this.customerDataClient.GetUserListAsync(content.Token);
                if (content.Result != null)
                {
                    userIds.AddRange(content.Result);
                }
            }
            
            ConcurrentBag<Customer> userDetails = new ConcurrentBag<Customer>();
            
            // here we are concurrently retrieving all user details with a maximum degree of parallelism
            // and saving it into a thread safe collection, i.e., a Concurrent Bag
            await userIds.ForEachAsync(MaxDegreeOfParallelism, async id =>
                {
                    Customer c = await this.customerDataClient.GetUserDetailsAsync(id);
                    userDetails.Add(c);
                });


            // Get the youngest users with Valid Phone Numbers and sort the list by their name
            // Phone number validation is very simple here, but we could potentially do more thorough validation 
            // based on specific application requirement

            // Here we are using the Linq operations to sort. However, if the number of items is in very large numbers(in millions), 
            // we could use a more efficient algorithm like Selection Rank 

            List<Customer> youngestUsers = userDetails
                                    .Where(c => Utils.IsValidPhoneNo(c.Number)) // consider only those with valid phone number
                                    .OrderBy(c => c.Age)                        // sort by age
                                    .Take(count)                                // get the top count users
                                    .OrderBy(c=>c.Name)                         // sort by the customer name
                                    .ToList();

            return youngestUsers;
        }
开发者ID:seemajlk,项目名称:CustomerDataProcessing,代码行数:57,代码来源:Processor.cs

示例5: Notify

        public override void Notify(ConcurrentBag<AMQPQueueMetric> busyQueues,
            ConcurrentBag<AMQPQueueMetric> quietQueues) {
            if (busyQueues.Any()) {
                if (!amqpAdapter.IsConnected)
                    amqpAdapter.Connect();

                Parallel.ForEach(busyQueues, amqpQueueMetric => amqpAdapter.Publish(ScaleMessage.Create(ScaleDirective.Out),
                    exchangeName, amqpQueueMetric.QueueName));
            }

            if (!quietQueues.Any()) return;
            if (!amqpAdapter.IsConnected)
                amqpAdapter.Connect();

            Parallel.ForEach(quietQueues.Where(q => !q.AMQPQueueMetricAnalysisResult.Equals(AMQPQueueMetricAnalysisResult.Stable)), amqpQueueMetric => amqpAdapter.Publish(ScaleMessage.Create(ScaleDirective.In),
                exchangeName, amqpQueueMetric.QueueName));
        }
开发者ID:yonglehou,项目名称:Daishi.AMQP,代码行数:17,代码来源:RabbitMQConsumerNotifier.cs

示例6: worker_DoWork


//.........这里部分代码省略.........
                            photoStorage.Add(pObj);
                            Interlocked.Increment(ref totalCount);
                        }
                    }
                    catch (Exception ex)
                    {
                        // an error happened
                        Console.WriteLine(ex.Message);
                        throw new Exception(ex.Message);
                    }
                }

                Interlocked.Increment(ref processedCount);
                progressValue = (int)(100.0f / totalCount * processedCount);
                self.ReportProgress(progressValue, "Reading products");

            });

            // in case when folder separation is needed, we create those folders
            if (cfg.DirectoryLimit > 0)
            {
                int numberOfDirectories = (int)Math.Ceiling((double)((float)photoStorage.Count / cfg.DirectoryLimit));
                for (int dn = 0; dn < numberOfDirectories; dn++)
                {
                    string subdir = (dn + 1).ToString("D4");
                    string dirPath = Path.Combine(cfg.Folder, subdir);
                    if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath);
                    var part = photoStorage.Skip(cfg.DirectoryLimit * dn).Take(cfg.DirectoryLimit);
                    foreach (Photo p in part)
                        p.SubDirectory = subdir;
                }
            }

            // download and update photos
            var unprocessedPhotos = photoStorage.Where(p => p.Status == PhotoStatus.New || p.Status == PhotoStatus.Downloaded).ToArray();
            while (unprocessedPhotos.Length > 0)
            {
                Parallel.ForEach(unprocessedPhotos, photo =>
                {
                    // download or convert
                    string folder = cfg.Folder;
                    if (!String.IsNullOrEmpty(photo.SubDirectory))
                        folder = Path.Combine(cfg.Folder, photo.SubDirectory);
                    string orgname = Path.Combine(folder, "org." + photo.FileName);
                    string destname = Path.Combine(folder, photo.FileName);

                    if (photo.Status == PhotoStatus.New)
                    {
                        // try download
                        DownloadResult result = Web.GetFile(photo.Uri, orgname);
                        switch (result)
                        {
                            case DownloadResult.NotFound:
                                // just skip the picture
                                photo.Status = PhotoStatus.Rejected;
                                break;
                            case DownloadResult.Error:
                                // try again
                                self.ReportProgress(progressValue, CONNECTION_ERROR);
                                Console.WriteLine("Failed {0}", photo.Uri);
                                Thread.Sleep(SLEEPING_TIME);
                                break;
                            case DownloadResult.Ok:
                                photo.Status = PhotoStatus.Downloaded;
                                Console.WriteLine("Read {0}", photo.Uri);
                                break;
                        }
                    }

                    if (photo.Status == PhotoStatus.Downloaded)
                    {
                        // try convert
                        if (Painter.ApplyPhoto(orgname, photo, cfg, destname))
                        {
                            photo.Status = PhotoStatus.Processed;
                            progressValue = (int)(100.0f / totalCount * Interlocked.Increment(ref processedCount));
                            try
                            {
                                // delete the original file
                                File.Delete(orgname);
                            }
                            catch (Exception) { }

                            self.ReportProgress(progressValue, "Downloading pictures");
                        }
                        else
                        {
                            self.ReportProgress(progressValue, CONVERSION_ERROR);
                        }
                    }

                });

                unprocessedPhotos = photoStorage.Where(p => p.Status == PhotoStatus.New || p.Status == PhotoStatus.Downloaded).ToArray();
            }

            e.Result = String.Format("Downloaded {0} pictures from {1} products",
                photoStorage.Count(p => p.Status == PhotoStatus.Processed),
                products.Count);
        }
开发者ID:Infarch,项目名称:MyPerlModules,代码行数:101,代码来源:MainForm.cs

示例7: Run

        public static IEnumerable<RunSummary> Run(IList<RunDescriptor> runDescriptors, IList<EndpointBehaviour> behaviorDescriptors, IList<IScenarioVerification> shoulds, Func<ScenarioContext, bool> done, int limitTestParallelismTo, Action<RunSummary> reports)
        {
            var totalRuns = runDescriptors.Count();

            var cts = new CancellationTokenSource();

            var po = new ParallelOptions
                {
                    CancellationToken = cts.Token
                };

            var maxParallelismSetting = Environment.GetEnvironmentVariable("max_test_parallelism");
            int maxParallelism;
            if (int.TryParse(maxParallelismSetting, out maxParallelism))
            {
                Console.Out.WriteLine("Parallelism limited to: {0}",maxParallelism);

                po.MaxDegreeOfParallelism = maxParallelism;
            }

            if (limitTestParallelismTo > 0)
                po.MaxDegreeOfParallelism = limitTestParallelismTo;

            var results = new ConcurrentBag<RunSummary>();

            try
            {
                Parallel.ForEach(runDescriptors, po, runDescriptor =>
                    {
                        if (po.CancellationToken.IsCancellationRequested)
                        {
                            return;
                        }

                        Console.Out.WriteLine("{0} - Started @ {1}", runDescriptor.Key, DateTime.Now.ToString());

                        var runResult = PerformTestRun(behaviorDescriptors, shoulds, runDescriptor, done);

                        Console.Out.WriteLine("{0} - Finished @ {1}", runDescriptor.Key, DateTime.Now.ToString());

                        results.Add(new RunSummary
                            {
                                Result = runResult,
                                RunDescriptor = runDescriptor,
                                Endpoints = behaviorDescriptors
                            });

                        if (runResult.Failed)
                        {
                            cts.Cancel();
                        }
                    });
            }
            catch (OperationCanceledException)
            {
                Console.Out.WriteLine("Test run aborted due to test failures");
            }

            var failedRuns = results.Where(s => s.Result.Failed).ToList();

            foreach (var runSummary in failedRuns)
            {
                DisplayRunResult(runSummary, totalRuns);
            }

            if (failedRuns.Any())
                throw new AggregateException("Test run failed due to one or more exception", failedRuns.Select(f => f.Result.Exception));

            foreach (var runSummary in results.Where(s => !s.Result.Failed))
            {
                DisplayRunResult(runSummary, totalRuns);

                if (reports != null)
                    reports(runSummary);
            }

            return results;
        }
开发者ID:petarvucetin,项目名称:NServiceBus,代码行数:78,代码来源:ScenarioRunner.cs

示例8: Dispose

        /// <summary>
        /// Dispose the current chain.
        /// </summary>
        public void Dispose()
        {
            knownChains = new ConcurrentBag<WorkerChain>(knownChains.Where(row => row != this));
            if (IsDisposed || IsDisposing)
                return;
            IsDisposing = true;

            if (workers[0] is TcpReceiver)
            {
                if (Side == ChainSide.SERVER_CONN)
                    TcpManager.DropServerConnection(this);
                else
                {
                    try
                    {
                        IPEndPoint addr = ((TcpReceiver)workers[0]).RemoteEndPoint;
                        TcpManager.DropClientConnection(addr);
                    }
                    catch
                    {
                    }
                }
            }

            foreach (var i in workers)
                i.Dispose();
            //((IDisposable)workers[0]).Dispose();

            //List<DataPacket> packets = new List<DataPacket>();
            /*lock (lockChainManagement)
            {*/
            // Unsubscribe all monitors used by a given client (used only by client chains)
            foreach (var monitor in Subscriptions)
            {
                Handlers.EventAdd.Unsubscribe(monitor.Value);
            }
            //}

            // Remove channel subscriptions
            foreach (var i in ChannelSubscriptions)
            {
                Record r = InfoService.SubscribedChannel[i.Key];
                if (r == null)
                    continue;
                foreach (var j in r.SubscriptionList)
                {
                    InfoService.ChannelSubscription.Remove(j);
                    CidGenerator.ReleaseCid(j);
                }
                Debug.Assert(r.GWCID != null, "r.GWCID != null");
                InfoService.ChannelSubscription.Remove(r.GWCID.Value);
                CidGenerator.ReleaseCid(r.GWCID.Value);
                InfoService.SubscribedChannel.Remove(i.Key);
            }

            // Remove all channels linked to this chain (used only by IOC chains)
            foreach (string channel in Channels)
            {
                //InfoService.SearchChannelEndPoint.Remove(channel);

                if (Log.WillDisplay(System.Diagnostics.TraceEventType.Verbose))
                    Log.TraceEvent(System.Diagnostics.TraceEventType.Verbose, ChainId, "Dropping channel " + channel);
                List<WorkerChain> channelsToDrop;
                /*lock (lockChainManagement)
                {
                    channelsToDrop = knownChains
                        .Where(row => row.Side != ChainSide.SERVER_CONN && row.ChannelCid.ContainsKey(channel)).ToList();
                }*/
                channelsToDrop = knownChains
                        .Where(row => row.Side != ChainSide.SERVER_CONN && row.ChannelCid.ContainsKey(channel)).ToList();
                // Disonnect all clients which use a channel
                foreach (WorkerChain chain in channelsToDrop)
                    chain.Dispose();

                /*// Send CA_PROTO_SERVER_DISCONN to all clients which use a channel
                foreach (WorkerChain chain in channelsToDrop)
                {
                    DataPacket newPacket = DataPacket.Create(0, this);
                    newPacket.Command = 27;
                    newPacket.Parameter1 = chain.ChannelCid[channel];
                    newPacket.Destination = chain.ClientEndPoint;
                    TcpManager.SendClientPacket(newPacket);
                    InfoService.ChannelCid.Remove(chain.ChannelCid[channel]);
                    CidGenerator.ReleaseCid(chain.ChannelCid[channel]);
                }*/
                try
                {
                    Record record = InfoService.ChannelEndPoint[channel];
                    if (record != null && record.GWCID != null)
                    {
                        InfoService.ChannelCid.Remove(record.GWCID.Value);
                        CidGenerator.ReleaseCid(record.GWCID.Value);
                    }
                    InfoService.ChannelEndPoint.Remove(channel);
                }
                catch
                {
//.........这里部分代码省略.........
开发者ID:ISISComputingGroup,项目名称:EPICS-epicssharp,代码行数:101,代码来源:WorkerChain.cs

示例9: checkAllNow

        internal static void checkAllNow(string baseFolder, Action<int> callbackProgress, Action callbackDone)
        {
            var allTasks = new ConcurrentBag<Task>();
            foreach(var bm in Bookmark.AllBookmarks)
            {
                allTasks.Add(bm.check(baseFolder));
            }

            Task.Run(() =>
            {
                    var tasks = allTasks.Where(n => n != null);
                 	var callback = callbackProgress;
                 	var callbackFinished = callbackDone;
                 	while(tasks.Any(n => n.Status == TaskStatus.Running ||
                 	                     n.Status == TaskStatus.Created ||
                 	                     n.Status == TaskStatus.WaitingForActivation ||
                 	                     n.Status == TaskStatus.WaitingForChildrenToComplete ||
                 	                     n.Status == TaskStatus.WaitingToRun))
                 	{
                 		var percent = 100.0 / (float)tasks.Count() * (float)(tasks.Count(n => n.Status == TaskStatus.Canceled) +
                 		                                            tasks.Count(n => n.Status == TaskStatus.RanToCompletion) +
                 		                                            tasks.Count(n => n.Status == TaskStatus.Faulted));
                 		callback((int)percent);
                 		Task.Delay(TimeSpan.FromSeconds(0.5)).Wait();
                 	}

                 	callbackFinished();
            });
        }
开发者ID:SommerEngineering,项目名称:OceanBookmarks,代码行数:29,代码来源:Bookmark.cs

示例10: NotifyToMaster

 public async Task NotifyToMaster(ConcurrentBag<IMessageDispatcher> dispatcher, Guid clientId, ClientType clientType)
 {
     var masterDispatcher = (IMasterMessageDispatcher)dispatcher.Where(x => x.ClientType == ClientType.Master).FirstOrDefault();
     if (masterDispatcher != null)
         await masterDispatcher.SendConnectAsJsonAsync(clientId, clientType);
 }
开发者ID:gencebay,项目名称:CloudBuilder,代码行数:6,代码来源:SocketRequestMiddleware.cs

示例11: DispatchesMessages

		public void DispatchesMessages()
		{
			const int numberOfMessages = 1000;

			var settings = new MessageDispatcherSettings();

			settings.InputChannel.WithDefault(new InMemoryMessageChannel());
			settings.InvalidChannel.WithDefault(new InMemoryMessageChannel());
			settings.MessageProcessorTypes.WithDefault(new List<Type> { typeof(FakeMessageProcessor) });
			settings.DurationOfDispatchingSlice.WithDefault(new TimeSpan(0, 0, 0, 0, 200));
			settings.NumberOfMessagesToDispatchPerSlice.WithDefault(30);

			_dispatcher.Configure(settings);

			_dispatcher.Enable();

			Assert.AreEqual(MessageDispatcherState.Enabled, _dispatcher.State);

			_transport.Open();

			var recordIds = new ConcurrentBag<Guid>();

			var start = DateTime.Now;

			for (var j = 0; j < numberOfMessages; j++)
			{
				var record = GetRecord();
				_transport.Send(record);
				recordIds.Add(record.Identifier);
			}

			Console.WriteLine("Sent 1000 messages in {0} ms", (DateTime.Now - start).TotalMilliseconds);

			Console.WriteLine("Waiting for messages to be processed");

			start = DateTime.Now;

			Assert.AreEqual(numberOfMessages, recordIds.Count);

			var numberOfMessagesProcessed = 0;

			do
			{
				Thread.Sleep(200);

				numberOfMessagesProcessed = recordIds.Where(id => _registry.GetPublicationRecord(id).Completed).Count();

				Console.WriteLine("{0} messages processed", numberOfMessagesProcessed);
			}
			while (numberOfMessagesProcessed < recordIds.Count());

			Console.WriteLine("Completed in {0} seconds", (DateTime.Now - start).TotalSeconds);

			_dispatcher.Disable();

			Assert.AreEqual(MessageDispatcherState.Disabled, _dispatcher.State);

			Assert.IsTrue(FakeMessageProcessor.ProcessedAnyMessages);
		}
开发者ID:smhinsey,项目名称:Euclid,代码行数:59,代码来源:MessageDispatcherTests.cs

示例12: AnalyzeFile


//.........这里部分代码省略.........
                            }
                        }
                        foreach (Regex exclude in excludeRegexList)
                        {
                            if (exclude.IsMatch(dscResourceRule.GetName()))
                            {
                                excludeRegexMatch = true;
                            }
                        }
                        if ((includeRule == null || includeRegexMatch) && (excludeRule == null || !excludeRegexMatch))
                        {
                            WriteVerbose(string.Format(CultureInfo.CurrentCulture, Strings.VerboseRunningMessage, dscResourceRule.GetName()));

                            // Ensure that any unhandled errors from Rules are converted to non-terminating errors
                            // We want the Engine to continue functioning even if one or more Rules throws an exception
                            try
                            {
                                var records = Helper.Instance.SuppressRule(dscResourceRule.GetName(), ruleSuppressions, dscResourceRule.AnalyzeDSCResource(ast, filePath).ToList());
                                foreach (var record in records.Item2)
                                {
                                    diagnostics.Add(record);
                                }
                                foreach (var suppressedRec in records.Item1)
                                {
                                    suppressed.Add(suppressedRec);
                                }
                            }
                            catch (Exception dscResourceRuleException)
                            {
                                WriteError(new ErrorRecord(dscResourceRuleException, Strings.RuleErrorMessage, ErrorCategory.InvalidOperation, filePath));
                            }
                        }
                    }

                }
            }
            #endregion

            #region Run External Rules

            if (ScriptAnalyzer.Instance.ExternalRules != null)
            {
                List<ExternalRule> exRules = new List<ExternalRule>();

                foreach (ExternalRule exRule in ScriptAnalyzer.Instance.ExternalRules)
                {
                    if ((includeRule == null || includeRule.Contains(exRule.GetName(), StringComparer.OrdinalIgnoreCase)) &&
                        (excludeRule == null || !excludeRule.Contains(exRule.GetName(), StringComparer.OrdinalIgnoreCase)))
                    {
                        string ruleName = string.Format(CultureInfo.CurrentCulture, "{0}\\{1}", exRule.GetSourceName(), exRule.GetName());
                        WriteVerbose(string.Format(CultureInfo.CurrentCulture, Strings.VerboseRunningMessage, ruleName));

                        // Ensure that any unhandled errors from Rules are converted to non-terminating errors
                        // We want the Engine to continue functioning even if one or more Rules throws an exception
                        try
                        {
                            exRules.Add(exRule);
                        }
                        catch (Exception externalRuleException)
                        {
                            WriteError(new ErrorRecord(externalRuleException, Strings.RuleErrorMessage, ErrorCategory.InvalidOperation, fileName));
                        }
                    }
                }

                foreach (var record in ScriptAnalyzer.Instance.GetExternalRecord(ast, tokens, exRules.ToArray(), this, fileName))
                {
                    diagnostics.Add(record);
                }
            }

            #endregion

            IEnumerable<DiagnosticRecord> diagnosticsList = diagnostics;

            if (severity != null)
            {
                var diagSeverity = severity.Select(item => Enum.Parse(typeof(DiagnosticSeverity), item, true));
                diagnosticsList = diagnostics.Where(item => diagSeverity.Contains(item.Severity));
            }

            //Output through loggers
            foreach (ILogger logger in ScriptAnalyzer.Instance.Loggers)
            {
                if (SuppressedOnly)
                {
                    foreach (DiagnosticRecord suppressRecord in suppressed)
                    {
                        logger.LogObject(suppressRecord, this);
                    }
                }
                else
                {
                    foreach (DiagnosticRecord diagnostic in diagnosticsList)
                    {
                        logger.LogObject(diagnostic, this);
                    }
                }
            }
        }
开发者ID:splatteredbits,项目名称:PSScriptAnalyzer,代码行数:101,代码来源:InvokeScriptAnalyzerCommand.cs

示例13: DCAwareRoundRobinPolicyWithNodesChanging

        public void DCAwareRoundRobinPolicyWithNodesChanging()
        {
            var hostList = new ConcurrentBag<Host>
            {
                TestHelper.CreateHost("0.0.0.1", "dc1"),
                TestHelper.CreateHost("0.0.0.2", "dc2"),
                TestHelper.CreateHost("0.0.0.3", "dc1"),
                TestHelper.CreateHost("0.0.0.4", "dc2"),
                TestHelper.CreateHost("0.0.0.5", "dc1"),
                TestHelper.CreateHost("0.0.0.6", "dc2"),
                TestHelper.CreateHost("0.0.0.7", "dc1"),
                TestHelper.CreateHost("0.0.0.8", "dc2"),
                TestHelper.CreateHost("0.0.0.9", "dc1"),
                TestHelper.CreateHost("0.0.0.10", "dc2")
            };
            const string localDc = "dc1";
            //to remove the host 3
            var hostToRemove = hostList.First(h => TestHelper.GetLastAddressByte(h) == 3);
            var clusterMock = new Mock<ICluster>();
            clusterMock
                .Setup(c => c.AllHosts())
                .Returns(() =>
                {
                    return hostList.ToList();
                });
            //Initialize the balancing policy
            var policy = new DCAwareRoundRobinPolicy(localDc, 1);
            policy.Initialize(clusterMock.Object);

            var hostYielded = new ConcurrentBag<IEnumerable<Host>>();
            Action action = () => hostYielded.Add(policy.NewQueryPlan(null, null).ToList());

            //Invoke without nodes changing
            TestHelper.ParallelInvoke(action, 100);
            Assert.True(hostYielded.Any(hl => hl.Any(h => h == hostToRemove)));

            var actionList = new List<Action>(Enumerable.Repeat<Action>(action, 1000));


            actionList.Insert(200, () =>
            {
                var host = TestHelper.CreateHost("0.0.0.11", "dc1");
                //raise event and then add
                clusterMock.Raise(c => c.HostAdded += null, host);
                hostList.Add(host);
            });
            actionList.Insert(400, () =>
            {
                var host = TestHelper.CreateHost("0.0.0.12", "dc1");
                //first add and then raise event
                hostList.Add(host);
                clusterMock.Raise(c => c.HostAdded += null, host);
            });
            
            actionList.Insert(400, () =>
            {
                var host = hostToRemove;
                hostList = new ConcurrentBag<Host>(hostList.Where(h => h != hostToRemove));
                clusterMock.Raise(c => c.HostRemoved += null, host);
            });

            //Invoke it with nodes being modified
            TestHelper.ParallelInvoke(actionList);
            //Clear the host yielded so far
            hostYielded = new ConcurrentBag<IEnumerable<Host>>();
            //Invoke it a some of times more in parallel
            TestHelper.ParallelInvoke(action, 100);
            //The removed node should not be returned
            Assert.False(hostList.Any(h => h == hostToRemove));
            Assert.False(hostYielded.Any(hl => hl.Any(h => h == hostToRemove)));
        }
开发者ID:mtf30rob,项目名称:csharp-driver,代码行数:71,代码来源:PoliciesUnitTests.cs

示例14: UpdateShows

        public void UpdateShows()
        {
            var lastFreshDate = DateTimeOffset.UtcNow.AddDays(-1);
            var showsNeedingUpdate = _session
                .Query<Show>()
                .Where(x => !x.HasEnded && x.LastUpdate < lastFreshDate)
                .ToList();
            var source = new EpGuideShowSource();
            var updatedShows = new ConcurrentBag<Tuple<Show, Show>>();
            Parallel.ForEach(
                showsNeedingUpdate,
                x => updatedShows.Add(Tuple.Create(x, source.FetchShowFromEpGuide(x.SourceId, x))));

            foreach (var i in updatedShows.Where(x => x.Item1 != null))
            {
                var originalShow = i.Item1;
                var updatedShow = i.Item2;
                _session.Advanced.Evict(originalShow);
                _session.Store(updatedShow);
            }
            _eventSink("watchlist");
        }
开发者ID:alundgren,项目名称:alun-tv,代码行数:22,代码来源:ShowUpdater.cs

示例15: WHEN_creating_1K_of_objects_THEN_can_change_property_to_an_object

        public void WHEN_creating_1K_of_objects_THEN_can_change_property_to_an_object()
        {
            var actors = new ConcurrentBag<TestActor>();

            for (int i = 0; i < 1000; i++)
            {
                var id = Guid.NewGuid();
                actors.Add(new TestActor { Id = id, Payload = string.Format("Actor Id: {0}", id.ToString()) });
            }

            Assert.AreEqual(1000, actors.Count);

            // Change property by a variable that reference the element in the collection
            var actor = actors.First();
            Assert.AreNotEqual(Guid.Empty, actor.Id);

            actor.Id = Guid.Empty;
            Assert.AreEqual(Guid.Empty, actors.First().Id);

            // Change property directly to the element in the collection
            Assert.AreNotEqual(Guid.Empty, actors.Last().Id);
            actors.Last().Id = Guid.Empty;
            Assert.AreEqual(Guid.Empty, actors.Last().Id);

            // Changing property in a loop
            Assert.IsTrue(actors.Where(a => a.Id != Guid.Empty).Any());
            foreach (var a in actors)
            {
                a.Id = Guid.Empty;
            }
            Assert.IsFalse(actors.Where(a => a.Id != Guid.Empty).Any());
        }
开发者ID:Narvalex,项目名称:EventCentric,代码行数:32,代码来源:InMemoryObjectsPerformance.cs


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