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


C# ConcurrentBag.Select方法代码示例

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


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

示例1: OSCADObject_ParallelObjectCreationDoesNotYieldDuplicateIds

        public void OSCADObject_ParallelObjectCreationDoesNotYieldDuplicateIds()
        {
            ConcurrentBag<OSCADObject> bag = new ConcurrentBag<OSCADObject>();

            Parallel.For(0, 1000, (i) => {
                bag.Add(new Sphere());
            });

            var ids = bag.Select(obj => obj.Id).ToList();
            Assert.AreEqual(ids.Count, ids.Distinct().Count());
        }
开发者ID:Exolun,项目名称:OSCADSharp,代码行数:11,代码来源:OSCADObjectTests.cs

示例2: Multiple_scheduled_commands_having_the_some_causative_command_etag_have_repeatable_and_unique_etags

        public async Task Multiple_scheduled_commands_having_the_some_causative_command_etag_have_repeatable_and_unique_etags()
        {
            var senderId = Any.Word();

            await Save(new NonEventSourcedCommandTarget(senderId));

            var targetIds = new[] { Any.Word(), Any.Word(), Any.Word() };

            var results = new ConcurrentBag<RequestReply>();

            Configuration.Current
                         .TraceScheduledCommands(
                             onScheduling: cmd =>
                             {
                                 var requestReply = ((dynamic) cmd).Command as RequestReply;
                                 if (requestReply != null)
                                 {
                                     results.Add(requestReply);
                                 }
                             });

            var initialEtag = "initial".ToETag();

            var firstCommand = new SendRequests(targetIds)
                               {
                                   ETag = initialEtag
                               };

            var scheduledCommand = new ScheduledCommand<NonEventSourcedCommandTarget>(
                firstCommand,
                senderId);

            await Deliver(scheduledCommand);

            var secondCommand = new SendRequests(targetIds)
                                {
                                    ETag = initialEtag
                                };

            scheduledCommand = new ScheduledCommand<NonEventSourcedCommandTarget>(
                secondCommand,
                senderId);

            // redeliver
            await Deliver(scheduledCommand);

            results.Should().HaveCount(6);
            results.Select(r => r.ETag)
                   .Distinct()
                   .Should()
                   .HaveCount(3);
        }
开发者ID:KimberlyPhan,项目名称:Its.Cqrs,代码行数:52,代码来源:CommandSchedulingTests_NonEventSourced.cs

示例3: GenerateAssemblyReferenceGraph

        public BidirectionalGraph<AssemblyVertex, EquatableEdge<AssemblyVertex>> GenerateAssemblyReferenceGraph(IEnumerable<Regex> exclusions, ConcurrentBag<string> files, bool verbose)
        {
            if (verbose) Console.WriteLine("Processing {0} files.", files.Count);
            var edges = new ConcurrentBag<EquatableEdge<AssemblyVertex>>();
            var current = 0;
            var total = files.Count;
            Parallel.ForEach(files, file =>
                {
                    if (verbose) Console.Write("\rProcessing file: {0} of {1}", ++current, total);
                    AssemblyDefinition assembly;
                    try
                    {
                        assembly = AssemblyDefinition.ReadAssembly(new MemoryStream(_fileSystem.File.ReadAllBytes(file)));
                    }
                    catch (Exception)
                    {
                        if (verbose) Console.WriteLine("Skipping file as it does not appear to be a .Net assembly: {0}", file);
                        return;
                    }
                    foreach (var reference in assembly.MainModule.AssemblyReferences)
                    {
                        var exists = files.Any(f =>
                            {
                                var fileInfo = new FileInfo(f);
                                return reference.Name.Equals(fileInfo.Name.Replace(fileInfo.Extension, ""), StringComparison.OrdinalIgnoreCase);
                            });
                        if (!exists)
                        {
                            string assemblyPath;
                            exists = _gacResolver.AssemblyExists(reference.FullName, out assemblyPath);
                        }
                        var assemblyName = new AssemblyName(assembly.FullName);
                        edges.Add(CreateNewEdge(reference, exists, assemblyName, exclusions));
                    }
                });

            if (verbose) Console.WriteLine();
            if (verbose) Console.WriteLine("Creating Graph...");
            var graph = new BidirectionalGraph<AssemblyVertex, EquatableEdge<AssemblyVertex>>();
            var allVertices = edges.Select(e => e.Source).Concat(edges.Select(e => e.Target));
            var distinctVertices = allVertices.Distinct();
            graph.AddVertexRange(distinctVertices);
            graph.AddEdgeRange(edges);
            return graph;
        }
开发者ID:kl4w,项目名称:ReferenceChecker,代码行数:45,代码来源:AssemblyReferenceGrapher.cs

示例4: button2_Click

        private void button2_Click(object sender, EventArgs e)
        {
            Trace.WriteLine(string.Format("{0} {1}", DateTime.Now.TimeOfDay, "开始整理报表数据源"));
            var listFile = new List<string>();
            //取数据
            if (cbxLogFile.Text == "")
            {
                listFile.AddRange(cbxLogFile.DataSource as List<string>);
            }
            else
            {
                listFile.Add(cbxLogFile.Text);
            }

            var list = new ConcurrentBag<Dictionary<string, Dictionary<string, LogEntity>>>();
            Parallel.ForEach(listFile, new ParallelOptions { MaxDegreeOfParallelism = IISHelper.MaxDegreeOfParallelism }, p =>
            // listFile.ForEach(p =>
            {
                if (string.IsNullOrEmpty(p))
                {
                    return;
                }
                var statTime = DateTime.Now;
                Trace.WriteLine(string.Format("{0} {1}", DateTime.Now.TimeOfDay, "讀" + p));
                var str = File.ReadAllText(p + ".json.txt");
                Trace.WriteLine(string.Format("{0} {1}", DateTime.Now.TimeOfDay, "讀" + p + ".end"));

                var dict2 = str.FromJson<Dictionary<string, Dictionary<string, LogEntity>>>();
                var dict = new Dictionary<string, Dictionary<string, LogEntity>>(dict2, StringComparer.OrdinalIgnoreCase);

                if (txtURL.Text != "")
                {

                    if (dict.ContainsKey(txtURL.Text))
                    {
                        dict = new Dictionary<string, Dictionary<string, LogEntity>> { { txtURL.Text, dict[txtURL.Text] } };
                        list.Add(dict);
                    }

                }
                else
                {
                    list.Add(dict);
                }
                Trace.WriteLine(string.Format("{0} {1}", DateTime.Now.TimeOfDay, "插入完成" + p + (DateTime.Now - statTime)));

            });

            Trace.WriteLine(string.Format("{0} {1}", DateTime.Now.TimeOfDay, "收集完数据"));
            var result = list.Select(p => p.Select(x => x.Value.Select(y => new ReportEntity
            {
                URL = x.Key,
                DateTime = DateTime.Parse(y.Key.PadRight(16, '0')).AddHours(8),
                DateTimeStr = y.Key,
                TimeSum = y.Value.TimeSum,
                TimeAvg = y.Value.TimeAvg
            }))).SelectMany(p => p).SelectMany(p => p).OrderBy(p => p.URL).ThenBy(p => p.DateTime).ToList();

            Trace.WriteLine(string.Format("{0} {1} Count:{2}", DateTime.Now.TimeOfDay, "整理报表数据源完成", result.Count));

            var sb = new StringBuilder();

            //.AddMonths(-1)不然顯示有問題
            if (chkAvg.Checked)
            {
                result.ForEach(p =>
                {
                    sb.AppendFormat(",[Date.UTC({0}),{1}]\r\n", p.DateTime.AddMonths(-1).ToString("yyyy,MM,dd,HH,mm"), p.TimeAvg);
                });
            }
            else
            {
                result.ForEach(p =>
                {
                    sb.AppendFormat(",[Date.UTC({0}),{1}]\r\n", p.DateTime.AddMonths(-1).ToString("yyyy,MM,dd,HH,mm"), p.TimeSum);
                });
            }

            var strResult = File.ReadAllText("Template\\1.html").Replace("{Data}", sb.ToString().Substring(1));
            File.WriteAllText(string.Format("Result.{0}.{1}.html",DateTime.Now.Ticks,txtURL.Text.Replace("/",".")), strResult);
            Trace.WriteLine(string.Format("{0} {1}", DateTime.Now.TimeOfDay, "输出HTML完成"));
        }
开发者ID:ToddZhao,项目名称:IISLog,代码行数:82,代码来源:FrmReport.cs

示例5: CheckXMLPackageAndApply

		/// <summary>
		/// Check the XML Package Given for Replace or Insert Apply
		/// </summary>
		/// <param name="xml">FileInfo for XML Package</param>
		/// <param name="replace">Enforce Replace Mode</param>
		/// <returns>True if success, False if any errors</returns>
		private bool CheckXMLPackageAndApply(FileInfo xml, bool replace)
		{
			
			var packageName = string.Format("{0}{1}{2}", xml.Directory.Name, Path.DirectorySeparatorChar, xml.Name);
			
			if (log.IsInfoEnabled)
				log.InfoFormat("Auto Loading XML File {0} into Database (Mode:{1})", packageName, replace ? "Replace" : "Insert");
			
			var result = true;
			
			try
			{
				//Load the XML File
				var xmlTable = LoaderUnloaderXML.LoadXMLTableFromFile(xml);
				if (xmlTable.Length > 0)
				{
					// Guess Object Type
					var xmlType = xmlTable.First().GetType();
					var tableHandler = new DataTableHandler(xmlType);
					
					// Find unique Fields
					var uniqueMember = DatabaseUtils.GetUniqueMembers(xmlType);
					
					// Get all object "Method" Through Reflection
					var classMethod = GameServer.Database.GetType().GetMethod("SelectAllObjects", Type.EmptyTypes);
					var genericMethod = classMethod.MakeGenericMethod(xmlType);
					var existingObjects = ((IEnumerable)genericMethod.Invoke(GameServer.Database, new object[]{})).Cast<DataObject>().ToArray();
					
					// Store Object to Alter
					var toDelete = new ConcurrentBag<DataObject>();
					var toAdd = new ConcurrentBag<DataObject>();
					
					// Check if an Object already exists
					xmlTable.AsParallel().ForAll(obj => {
					                             	// Check if Exists Compare Unique and Non-Generated Primary Keys
					                             	var exists = existingObjects
					                             		.FirstOrDefault(entry => uniqueMember
					                             		                .Any(constraint => constraint
					                             		                     .All(bind => bind.ValueType == typeof(string)
					                             		                          ? bind.GetValue(entry).ToString().Equals(bind.GetValue(obj).ToString(), StringComparison.OrdinalIgnoreCase)
					                             		                          : bind.GetValue(entry) == bind.GetValue(obj)))
					                             		               );
					                             	
					                             	if (exists != null)
					                             	{
					                             		if (replace)
					                             		{
					                             			// Delete First
					                             			toDelete.Add(exists);
					                             			toAdd.Add(obj);
					                             		}
					                             		// Silently ignore duplicate inserts only...
					                             	}
					                             	else
					                             	{
					                             		toAdd.Add(obj);
					                             	}
					                             });
					// Delete First
					foreach (var obj in toDelete)
						obj.AllowDelete = true;
					
					GameServer.Database.DeleteObject(toDelete);
					
					// Then Insert
					var previousAllowAdd = toAdd.Select(obj => obj.AllowAdd).ToArray();
					foreach (var obj in toAdd)
						obj.AllowAdd = true;
					
					GameServer.Database.AddObject(toAdd);
					
					// Reset Allow Add Flag
					var current = 0;
					foreach (var obj in toAdd)
					{
						obj.AllowAdd = previousAllowAdd[current];
						current++;
					}
				}
				else
				{
					if (log.IsWarnEnabled)
						log.WarnFormat("XML Package {0} Found Empty, may be a parsing Error...", packageName);
					result = false;
				}
			}
			catch (Exception e)
			{
				if (log.IsErrorEnabled)
					log.ErrorFormat("Error While Loading XML Package {0} into Database (Mode:{1}) - {2}", packageName, replace ? "Replace" : "Insert", e);
				result = false;
			}
			
			return result;
//.........这里部分代码省略.........
开发者ID:dol-leodagan,项目名称:DOLSharp,代码行数:101,代码来源:AutoXMLDatabaseUpdate.cs

示例6: Post

        public async Task<HttpResponseMessage> Post(string username)
        {
            if (!AuthorizeToUsername(username))
            {
                Logger.Error("Cannot upload to another users folder");
                return Request.CreateResponse(HttpStatusCode.Unauthorized, "Cannot upload to another users folder");
            }

            if (!Request.Content.IsMimeMultipartContent())
            {
                Logger.Error("Must be a multipart content type");
                return Request.CreateResponse(HttpStatusCode.BadRequest, "Must be a multipart content type!");
            }

            // Proceed - everything OK
            var provider = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());
            var bag = new ConcurrentBag<Image>();

            var tasks = provider.Contents.Select(async file =>
            {
                // Process individual image
                Logger.Trace("Processing image...");
                var handler = imageHandleFactory.GetImageHandler();
                var user = Request.GetUser().ValueOrFailure();
                var image = await handler.ProcessUserImage(user, file, "");

                // Add images to the collection
                bag.Add(image);
            });

            // Wait for all images to be processed
            await Task.WhenAll(tasks);
            var error = true;
            int imageID = -1;
            var quotaKb = Properties.Settings.Default.quotaKB;

            var save = bag.Select(async image =>
            {
                var onCreated = new Func<Image, Task<bool>>(async img =>
                {
                    var dto = Construct(img);
                    webSocketService.NewImage(dto);

                    return await whatsNew.AddItem(img.ID, NewsType.ImageUpload) > 0;
                });

                var created = await userImageRepository.Create(image, onCreated);
                created.Match(
                    (img) =>
                    {
                        Logger.Debug("Saved image: {0}.{1}\tWith ID: {2}", img.Filename, img.Extension, img.ID);
                        imageID = img.ID;
                        error = false;
                    },
                    () =>
                    {
                        Logger.Error("Could not save: {0}.{1}", image.Filename, image.Extension);
                    });
            });

            await Task.WhenAll(save);

            var response = string.Format("Finished uploading {0} file(s)", bag.Count);
            return (!error) ?
                Request.CreateResponse(HttpStatusCode.Created, response) :
                Request.CreateResponse(HttpStatusCode.InternalServerError,
                   "Could not save file. Possible reasons: File already exists or database error. See log files for more information.");
        }
开发者ID:inuplan,项目名称:intranet,代码行数:68,代码来源:UserImageController.cs

示例7: UpdateMultiple

        async Task<string[]> UpdateMultiple(IReadOnlyCollection<Package.ObjectMap> objects,
            IReadOnlyCollection<Package> packages,
            IReadOnlyCollection<Uri> remotes) {
            if (!objects.Any()) {
                Repository.Log("No remote objects to resolve");
                return new string[0];
            }
            Repository.Log("Resolving {0} remote objects for {1} packages from {2} remotes, please be patient..",
                objects.Count, packages.Count, remotes.Count);

            var doneObjects = new ConcurrentBag<FileObjectMapping>();

            var relObjects = objects.OrderByDescending(x => Tools.FileUtil.SizePrediction(x.FO.FilePath))
                .Select(x => new FileFetchInfo(Repo.GetObjectSubPath(x.FO), x.FO.FilePath) {
                    ExistingPath = x.ExistingObject != null ? Repo.GetObjectSubPath(x.ExistingObject) : null,
                    OnComplete = () => doneObjects.Add(x.FO)
                })
                .ToArray();

            StatusRepo.Reset(RepoStatus.Downloading, objects.Count);
            StatusRepo.ProcessSize(GetExistingObjects(objects.Select(x => x.FO), packages), Repo.ObjectsPath,
                GetPackedSize(packages));
            try {
                await
                    Package.DownloadObjects(remotes, StatusRepo, relObjects, Repo.ObjectsPath).ConfigureAwait(false);
            } finally {
                Repo.ReAddObject(doneObjects.Select(x => x.Checksum).ToArray());
            }

            return relObjects.Select(x => x.FilePath).ToArray();
        }
开发者ID:SIXNetworks,项目名称:withSIX.Desktop,代码行数:31,代码来源:PackageManager.cs

示例8: When_multiple_projectors_are_subscribed_then_data_that_both_projections_have_seen_is_not_requeried

        public async Task When_multiple_projectors_are_subscribed_then_data_that_both_projections_have_seen_is_not_requeried()
        {
            var queriedEvents = new ConcurrentBag<IDomainEvent>();

            var balanceProjections = new InMemoryProjectionStore<BalanceProjection>();
            await balanceProjections.Put(streamId, new BalanceProjection
            {
                CursorPosition = 2
            });
            var catchup = StreamCatchup.Create(stream.Trace(onResults: (q, b) =>
            {
                foreach (var e in b)
                {
                    queriedEvents.Add(e);
                }
            }), batchCount: 10);
            catchup.Subscribe(new BalanceProjector(), balanceProjections);

            store.WriteEvents(streamId, howMany: 2);

            await catchup.RunSingleBatch();
            queriedEvents.Count
                         .Should()
                         .Be(1,
                             "the first two events should be skipped because of the starting cursor position");
            queriedEvents.Should()
                         .ContainSingle(e => e.StreamRevision == 3,
                                        "only the most recent event should be queried");

            var accountHistoryProjections = new InMemoryProjectionStore<AccountHistoryProjection>();
            await accountHistoryProjections.Put(streamId, new AccountHistoryProjection
            {
                CursorPosition = 2
            });
            catchup.Subscribe(new AccountHistoryProjector(), accountHistoryProjections);

            store.WriteEvents(streamId);

            await catchup.RunSingleBatch();

            queriedEvents.Select(e => e.StreamRevision)
                         .ShouldBeEquivalentTo(new[] { 3, 3, 4 },
                                               "event 3 needs to be repeated because the newly-subscribed aggregator hasn't seen it yet");
        }
开发者ID:MrPiotr,项目名称:Alluvial,代码行数:44,代码来源:SingleStreamCatchupTests.cs

示例9: ParallelTaskWithOneActionTest

		public void ParallelTaskWithOneActionTest()
		{
			var timings = new ConcurrentBag<Timing>();

			Action action = () =>
			{
				var timing = new Timing();

				timing.StartTime = DateTime.Now;
				Thread.Sleep(500);
				timing.FinishTime = DateTime.Now;

				timings.Add(timing);
			};

			var task = ParallelTask.StartNew(action, 10);
			task.Wait();

			DateTime maxStartTime = timings.Select(t => t.StartTime).Max();
			DateTime maxFinishTime = timings.Select(t => t.FinishTime).Min();

			foreach(var timing in timings)
			{
				Console.WriteLine(String.Format("{0} - {1}", timing.StartTime, timing.FinishTime));
			}

			Assert.IsTrue(maxStartTime < maxFinishTime);
		}
开发者ID:toolmagic,项目名称:RepeatableTask,代码行数:28,代码来源:ParallelTaskTestSuite.cs

示例10: Multiple_contexts_running_concurrently_can_use_interception

        public void Multiple_contexts_running_concurrently_can_use_interception()
        {
            var loggers = new ConcurrentBag<CommandLogger>();

            const int executionCount = 5;
            ExecuteInParallel(
                () =>
                    {
                        using (var context = new BlogContextNoInit())
                        {
                            var logger = new CommandLogger(context);
                            DbInterception.Add(logger);
                            loggers.Add(logger);

                            try
                            {
                                BlogContext.DoStuff(context);
                            }
                            finally
                            {
                                DbInterception.Remove(logger);
                            }

                            var commandsUsed = new bool[Enum.GetValues(typeof(CommandMethod)).Length];

                            for (var i = 0; i < logger.Log.Count; i++)
                            {
                                var method = logger.Log[i].Method;
                                commandsUsed[(int)method] = true;

                                if (method.ToString().EndsWith("Executing"))
                                {
                                    Assert.Equal(method + 1, logger.Log[i + 1].Method);
                                    Assert.Same(logger.Log[i].Command, logger.Log[i + 1].Command);
                                }
                            }

                            // Check that expected command have log entries
                            Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuting]);
                            Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuted]);
                            Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuting]);
                            Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuted]);
#if !NET40
                            Assert.True(commandsUsed[(int)CommandMethod.NonQueryExecuting]);
                            Assert.True(commandsUsed[(int)CommandMethod.NonQueryExecuted]);
#endif

                            // Sanity check on command text
                            var commandTexts = logger.Log.Select(l => l.CommandText.ToLowerInvariant());
                            Assert.True(commandTexts.Any(c => c.StartsWith("select")));
                            Assert.True(commandTexts.Any(c => c.StartsWith("insert")));
#if !NET40
                            Assert.True(commandTexts.Any(c => c.StartsWith("update")));
#endif

                            // Sanity check on results
                            Assert.True(logger.Log.Where(l => l.Method == CommandMethod.NonQueryExecuted).All(l => l.Result != null));
                            Assert.True(logger.Log.Where(l => l.Method == CommandMethod.ReaderExecuted).All(l => l.Result != null));
                        }
                    }, executionCount);

            // Check that each execution logged exactly the same commands.

            Assert.Equal(executionCount, loggers.Count);

            var firstLog = loggers.First().Log;
            foreach (var log in loggers.Select(l => l.Log).Skip(1))
            {
                Assert.Equal(firstLog.Count, log.Count);

                for (var i = 0; i < log.Count; i++)
                {
                    Assert.Equal(firstLog[i].Method, log[i].Method);
                    Assert.Equal(firstLog[i].CommandText, log[i].CommandText);

                    if (firstLog[i].Result == null)
                    {
                        Assert.Null(log[i].Result);
                    }
                    else
                    {
                        Assert.Same(firstLog[i].Result.GetType(), log[i].Result.GetType());
                    }
                }
            }
        }
开发者ID:jesusico83,项目名称:Telerik,代码行数:86,代码来源:CommandInterceptionTests.cs

示例11: CanGenerate_Multithreaded

        public void CanGenerate_Multithreaded()
        {
            var ids = new ConcurrentBag<KeyValuePair<Int32, UInt64>>();

            var cts = new CancellationTokenSource();
            
            ParameterizedThreadStart generateIds = (token) =>
            {
                var ct = (CancellationToken)token;

                while (!ct.IsCancellationRequested)
                {
                    var newIds = new ulong[10000];
                    for (int i = 0; i < 10000; i++)
                    {
                        newIds[i] = _generator.Generate();
                    }

                    newIds.Run(x => ids.Add(KeyValuePair.Create(Thread.CurrentThread.ManagedThreadId, x)));
                }
            };

            var threads = new[]
            {
                new Thread(generateIds),
                new Thread(generateIds),
                new Thread(generateIds),
                new Thread(generateIds)
            };

            threads.Run(t => t.Start(cts.Token));

            Thread.Sleep(1000);

            cts.Cancel();

            threads.Run(t => t.Join());

            var distinctIds = ids.Select(x => x.Value).Distinct().ToArray();
            Assert.IsTrue(ids.Count > 0, "Count wasn't greater than zero.");
            Assert.IsTrue(ids.Count == distinctIds.Count(), "Counts don't match!");

            Console.WriteLine("Id count: {0}", ids.Count);

            var distinctThreadIds = ids.Select(x => x.Key).Distinct().ToArray();
            Assert.IsTrue(distinctThreadIds.Length > 1, "Distinct threads not greater than one.");
        }
开发者ID:iSynaptic,项目名称:iSynaptic.Core,代码行数:47,代码来源:InterleavingUniqueNumberGeneratorTests.cs

示例12: Catchup_can_query_downstream_streams_such_that_repeated_data_is_not_queried

        public async Task Catchup_can_query_downstream_streams_such_that_repeated_data_is_not_queried()
        {
            var store = this.store;
            var streamId = Guid.NewGuid().ToString();
            var queriedEvents = new ConcurrentBag<IDomainEvent>();

            var catchup = StreamCatchup.All(streamSource.StreamPerAggregate()
                                                        .Map(ss => ss.Select(s => s.Trace(onResults: (q, b) =>
                                                        {
                                                            foreach (var e in b)
                                                            {
                                                                queriedEvents.Add(e);
                                                            }
                                                        }))),
                                            Cursor.New("100"),
                                            batchSize: 1);
            catchup.Subscribe(new BalanceProjector());

            store.WriteEvents(streamId);
            await catchup.RunSingleBatch();
            queriedEvents.Select(e => e.StreamRevision)
                         .ShouldBeEquivalentTo(new[] { 1 });

            store.WriteEvents(streamId);
            await catchup.RunSingleBatch();
            queriedEvents.Select(e => e.StreamRevision)
                         .ShouldBeEquivalentTo(new[] { 1, 2 });

            store.WriteEvents(streamId);
            await catchup.RunSingleBatch();
            queriedEvents.Select(e => e.StreamRevision)
                         .ShouldBeEquivalentTo(new[] { 1, 2, 3 });
        }
开发者ID:gitter-badger,项目名称:Alluvial,代码行数:33,代码来源:MultiStreamCatchupTests.cs

示例13: FindUsages

        public FindUsagesResponse FindUsages(FindUsagesRequest request)
        {
            var res = _parser.ParsedContent(request.Buffer, request.FileName);
            var loc = new TextLocation(request.Line, request.Column);
            var result = new ConcurrentBag<AstNode>();
            var findReferences = new FindReferences();
            ResolveResult resolveResult = ResolveAtLocation.Resolve(res.Compilation, res.UnresolvedFile, res.SyntaxTree, loc);
            if (resolveResult is LocalResolveResult)
            {
                var variable = (resolveResult as LocalResolveResult).Variable;
                findReferences.FindLocalReferences(variable, res.UnresolvedFile, res.SyntaxTree, res.Compilation, (node, rr) => result.Add(node), CancellationToken.None);
            }
            else
            {
                IEntity entity = null;
                if (resolveResult is TypeResolveResult)
                {
                    entity = (resolveResult as TypeResolveResult).Type.GetDefinition();
                }

                if (resolveResult is MemberResolveResult)
                {
                    entity = (resolveResult as MemberResolveResult).Member;
                }

                if (entity == null)
                {
                    return new FindUsagesResponse {Usages = new List<Usage>()};
                }
                var searchScopes = findReferences.GetSearchScopes(entity);

                var interesting = new List<CSharpUnresolvedFile>();

                foreach (var scope in searchScopes)
                {
                    var scopeInteresting = findReferences.GetInterestingFiles(scope, res.Compilation);
                    interesting.AddRange(scopeInteresting);
                }

                Parallel.ForEach(interesting, file =>
                    {
                        ParsedResult parsedResult = _parser.ParsedContent(
                            _solution.GetFile(file.FileName).Content.Text, file.FileName);
                        findReferences.FindReferencesInFile(searchScopes, file, parsedResult.SyntaxTree,
                                                            parsedResult.Compilation,
                                                            (node, rr) => result.Add(node), CancellationToken.None);
                    });

            }

            var usages = result.Select(node => new Usage
            {
                FileName = node.GetRegion().FileName,
                Text = node.Preview(_solution.GetFile(node.GetRegion().FileName)).Replace("'", "''"),
                Line = node.StartLocation.Line,
                Column = node.StartLocation.Column,
            });

            return new FindUsagesResponse { Usages = usages };
        }
开发者ID:CSRedRat,项目名称:Omnisharp,代码行数:60,代码来源:FindUsagesHandler.cs

示例14: GenerateAssemblyReferenceGraph

        public BidirectionalGraph<AssemblyVertex, EquatableEdge<AssemblyVertex>> GenerateAssemblyReferenceGraph(IEnumerable<Regex> exclusions, IEnumerable<Regex> ignoring, ConcurrentBag<string> files, bool verbose, bool checkAssemblyVersionMatch = true)
        {
            if (verbose) Console.WriteLine("Processing {0} files.", files.Count);
            var edges = new ConcurrentBag<EquatableEdge<AssemblyVertex>>();
            var vertices = new List<AssemblyVertex>();
            var ignoreList = ignoring.ToList();
            var excludeList = exclusions.ToList();

            var current = 0;
            var total = files.Count;
            Parallel.ForEach(files, file =>
                {
                    if (verbose) Console.Write("\rProcessing file: {0} of {1}", ++current, total);
                    AssemblyDefinition assembly;
                    try
                    {
                        assembly = AssemblyDefinition.ReadAssembly(new MemoryStream(_fileSystem.File.ReadAllBytes(file)));
                    }       
                    catch (Exception)
                    {
                        if (verbose) Console.WriteLine("Skipping file as it does not appear to be a .Net assembly: {0}", file);
                        return;
                    }
                    //We need to load the assembly to ensure that the assembly name is the same as the file name (to be exact)
                    if (ignoreList.Any(i => i.IsMatch(assembly.Name.Name.ToLowerInvariant())))
                    {
                        if (verbose) Console.WriteLine("Ignoring file: {0}", file);
                        return;
                    }

                    //Check for 32bitness on our source assembly
                    var required32Bit = Required32BitSet(assembly);
                    var assemblyName = new AssemblyName(assembly.FullName);
 
                    //If we dont have references (I know, unlikely right?)
                    if (!assembly.MainModule.AssemblyReferences.Any())
                    {
                        vertices.Add(CreateAssemblyVertex(assemblyName.FullName, assemblyName.Name, true, Required32BitSet(assembly), excludeList));
                        return;
                    }

                    //Otherwise create edges for them...
                    foreach (var reference in assembly.MainModule.AssemblyReferences)
                    {
                        var foundFileMatch = files.Any(f => CheckDependentFileMatchesManifest(f, reference, checkAssemblyVersionMatch, required32Bit));

                        if (!foundFileMatch)
                        {
                            foundFileMatch = _gacResolver.AssemblyExists(reference.FullName);
                        }
                        if (!ignoreList.Any(i => i.IsMatch(reference.Name.ToLowerInvariant())))
                            edges.Add(CreateNewEdge(reference, foundFileMatch, required32Bit, assemblyName, excludeList));
                        else
                            if (verbose) Console.WriteLine("Ignoring: {0}",assemblyName.Name);
                    }
                });

            if (verbose) Console.WriteLine();
            if (verbose) Console.WriteLine("Creating Graph...");
            var graph = new BidirectionalGraph<AssemblyVertex, EquatableEdge<AssemblyVertex>>();
            var allVertices = edges.Select(e => e.Source).Concat(edges.Select(e => e.Target)).Concat(vertices);
            var distinctVertices = allVertices.Distinct();
            graph.AddVertexRange(distinctVertices);
            graph.AddEdgeRange(edges);
            return graph;
        }
开发者ID:modulexcite,项目名称:ReferenceChecker,代码行数:66,代码来源:AssemblyReferenceGrapher.cs

示例15: ParallelTaskWithMultipleActionsTest

		public void ParallelTaskWithMultipleActionsTest()
		{
			var actions = new Action[10];
			var timings = new ConcurrentBag<Timing>();

			for (int i = 0; i < actions.Length; i++)
			{
				actions[i] = () =>
				{
					var timing = new Timing();

					timing.StartTime = DateTime.Now;
					Thread.Sleep(500);
					timing.FinishTime = DateTime.Now;

					timings.Add(timing);
				};
			}

			var task = ParallelTask.StartNew(actions);
			task.Wait();

			DateTime maxStartTime = timings.Select(t => t.StartTime).Max();
			DateTime maxFinishTime = timings.Select(t => t.FinishTime).Min();

			foreach (var timing in timings)
			{
				Console.WriteLine(String.Format("{0} - {1}", timing.StartTime, timing.FinishTime));
			}

			Assert.IsTrue(maxStartTime < maxFinishTime);
		}
开发者ID:toolmagic,项目名称:RepeatableTask,代码行数:32,代码来源:ParallelTaskTestSuite.cs


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