public static void TestBasicScenarios() { ConcurrentBag<int> cb = new ConcurrentBag<int>(); Task[] tks = new Task[2]; tks[0] = Task.Run(() => { cb.Add(4); cb.Add(5); cb.Add(6); }); // Consume the items in the bag tks[1] = Task.Run(() => { int item; while (!cb.IsEmpty) { bool ret = cb.TryTake(out item); Assert.True(ret); // loose check if (item != 4 && item != 5 && item != 6) { Assert.False(true, "Expected: 4|5|6; actual: " + item.ToString()); } } }); Task.WaitAll(tks); }
public void AddItemTwice() { var bag = new ConcurrentBag<string>(); bag.Add("TEST"); bag.Add("TEST"); Assert.AreEqual(2, bag.Count); }
public void ParallelTest() { var _NumberOfItems = 100000; var _ConcurrentBag = new ConcurrentBag<UniqueTimestamps>(); var _Task1 = Task.Factory.StartNew(() => { Parallel.For(0, _NumberOfItems, i => { var _UniqueTS = new UniqueTimestamps(); _UniqueTS.ThreadId = Thread.CurrentThread.ManagedThreadId; _UniqueTS.Timestamp = UniqueTimestamp.Ticks; _ConcurrentBag.Add(_UniqueTS); }); }); var _Task2 = Task.Factory.StartNew(() => { Parallel.For(0, _NumberOfItems, j => { var _UniqueTS = new UniqueTimestamps(); _UniqueTS.ThreadId = Thread.CurrentThread.ManagedThreadId; _UniqueTS.Timestamp = UniqueTimestamp.Ticks; _ConcurrentBag.Add(_UniqueTS); }); }); Task.WaitAll(_Task1, _Task2); var _NumberOfThreads = (from item in _ConcurrentBag select item.ThreadId ).Distinct().Count(); var _NumberOfTimestamps = (from item in _ConcurrentBag select item.Timestamp).Distinct().Count(); Assert.AreEqual(_NumberOfThreads, Environment.ProcessorCount); Assert.AreEqual(_NumberOfTimestamps, 2 * _NumberOfItems); }
public void ThenAllTheConferencesAreCreated() { var failureCollector = new ConcurrentBag<string>(); Parallel.ForEach(slugs, s => { var mConf = ConferenceHelper.FindConference(s); if(mConf == null) { failureCollector.Add(string.Format("Conference with slug '{0}' not found in management repository.", s)); return; } var success = MessageLogHelper.CollectEvents<AvailableSeatsChanged>(mConf.Id, seatsInfo.Rows.Count); if(!success) { failureCollector.Add(string.Format("Some seats were not found in Conference '{0}'", mConf.Name)); } }); if(failureCollector.Count > 0) { var sb = new StringBuilder(); failureCollector.ToList().ForEach(s => sb.AppendLine(s)); Assert.True(failureCollector.Count == 0, sb.ToString()); // raise error with all the failures } }
static void Main(string[] args) { ConcurrentBag<int> bag = new ConcurrentBag<int>(); bag.Add(42); bag.Add(21); int result; if (bag.TryTake(out result)) { Console.WriteLine(result); } if (bag.TryPeek(out result)) { Console.WriteLine("There is a next item: {0}", result); } if (bag.TryTake(out result)) { Console.WriteLine(result); } Console.Write("Press a key to exit"); Console.ReadKey(); }
private static void DemoConcurrentBag() { Console.WriteLine("Demo Concurrent Bag ----------------------"); var shirts = new ConcurrentBag<string>(); shirts.Add("Pluralsight"); shirts.Add("WordPress"); shirts.Add("Code School"); Console.WriteLine("After enqueuing, count = " + shirts.Count); string item1; //= shirts.Dequeue(); bool success = shirts.TryTake(out item1); if (success) Console.WriteLine("\r\nRemoving " + item1); else Console.WriteLine("queue was empty"); string item2; //= shirts.Peek(); success = shirts.TryPeek(out item2); if (success) Console.WriteLine("Peeking " + item2); else Console.WriteLine("queue was empty"); Console.WriteLine("\r\nEnumerating:"); foreach (string item in shirts) Console.WriteLine(item); Console.WriteLine("\r\nAfter enumerating, count = " + shirts.Count); }
public World() { worldTime = new DateTime(); rooms = new List<Room>(); rooms.Add(new Room("The Void", "You are standing in the middle of nothing.")); mobs = new ConcurrentBag<NPC>(); NPC test = new NPC("mob", "A slimy sticky stinky mob", new Stats(50, 100), this); rooms.First().addNPC(test); mobs.Add(test); test = new NPC("bob", "A slimy sticky stinky bob", new Stats(50, 100), this); rooms.First().addNPC(test); mobs.Add(test); test = new NPC("sob", "A slimy sticky stinky sob", new Stats(50, 100), this); rooms.First().addNPC(test); mobs.Add(test); test = new NPC("cob", "A slimy sticky stinky cob", new Stats(50, 100), this); rooms.First().addNPC(test); mobs.Add(test); Merchant merch = new Merchant(); merch.name = "merchant"; merch.description = "a merchant of souls"; merch.world = this; merch.stats = new Stats(10000, 10000); Item i = new Item("health", "a potion of restore health", 1, "none", 1); merch.items.addToInventory(i); rooms.First().addNPC(merch); mobs.Add(merch); rooms.First().addItem(new Item("leggings", "a worn pair of leather leggings", 2, "legs", 2)); }
public static void TestBasicScenarios() { ConcurrentBag<int> cb = new ConcurrentBag<int>(); Task[] tks = new Task[2]; tks[0] = Task.Run(() => { cb.Add(4); cb.Add(5); cb.Add(6); }); // Consume the items in the bag tks[1] = Task.Run(() => { int item; while (!cb.IsEmpty) { bool ret = cb.TryTake(out item); Assert.True(ret); // loose check Assert.Contains(item, new[] { 4, 5, 6 }); } }); Task.WaitAll(tks); }
public void finish_successfully() { var handling = new AsyncHandling(ObjectMother.InvocationContext()); var list = new ConcurrentBag<string>(); var task1 = Task.Factory.StartNew(() => { Thread.Sleep(100); list.Add("A"); }); var task2 = Task.Factory.StartNew(() => { Thread.Sleep(100); list.Add("B"); }); var task3 = Task.Factory.StartNew(() => { Thread.Sleep(100); list.Add("C"); }); handling.Push(task1); handling.Push(task2); handling.Push(task3); handling.WaitForAll(); list.OrderBy(x => x).ShouldHaveTheSameElementsAs("A", "B", "C"); }
/// <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(); }
static void Main(string[] args) { ConcurrentBag<int> bag = new ConcurrentBag<int>(); bag.Add(123); bag.Add(321); bag.Add(123123); int result; if (bag.TryTake(out result)) { Console.WriteLine(result); } if (bag.TryTake(out result)) { Console.WriteLine(result); } if (bag.TryPeek(out result)) { Console.WriteLine("There is a next itam: {0}", result); } Console.ReadLine(); }
/// <summary> /// Создает тест с набором партиций и с возможными собственными шаблоном запроса и соединения /// </summary> /// <param name="query"> </param> /// <param name="connection"> </param> public AllPartitionsInParallelTest(string query = null,string connection=null) { _subtests = new ConcurrentBag<SinglePartitionQueryingTest>(); for (var year = START_YEAR; year <= END_YEAR; year++) { _subtests.Add(new SinglePartitionQueryingTest(year, HalfYear.First, query,connection)); _subtests.Add(new SinglePartitionQueryingTest(year, HalfYear.Second, query,connection)); } }
//ConcurrentCollectionTest public static void ConcurrentCollectionTest() { ConcurrentBag<string> bag = new ConcurrentBag<string>(); bag.Add("just a test!"); bag.Add("abc"); bag.Add("ARCAS"); string result; bag.TryPeek(out result); Console.WriteLine(result); BlockingCollection<string> collection = new BlockingCollection<string>(); }
public void Run() { ConcurrentBag<int> bag = new ConcurrentBag<int>(); bag.Add(42); bag.Add(21); int result; if (bag.TryTake(out result)) Console.WriteLine(result); if (bag.TryPeek(out result)) Console.WriteLine("There is a next item: {0}", result); }
private void Example2() { Console.WriteLine("With List multithreading throws an error"); //List<int> list = new List<int>(); //Task.Run(() => //{ // list.Add(21); // Thread.Sleep(250); // list.Add(43); // Thread.Sleep(500); // list.Remove(21); // Thread.Sleep(500); // list.Add(63); //}); //Task.Run(() => //{ // //foreach (int i in list) // //{ // // Thread.Sleep(500); // // Console.WriteLine(i); // //} // for(int i=0;i<list.Count;i++) // { // Thread.Sleep(500); // Console.WriteLine(list[i]); // } //}).Wait(); Console.WriteLine("With Concurrent Bag"); ConcurrentBag<int> concurrentBag = new ConcurrentBag<int>(); int result; Task.Run(() => { concurrentBag.Add(21); concurrentBag.Add(33); Thread.Sleep(250); concurrentBag.Add(43); Thread.Sleep(500); concurrentBag.Add(53); concurrentBag.TryTake(out result); Thread.Sleep(500); concurrentBag.Add(63); }); Task.Run(() => { foreach (int i in concurrentBag) { Thread.Sleep(500); Console.WriteLine(i); } }).Wait(); }
public override void Analyse(AMQPQueueMetric current, AMQPQueueMetric previous, ConcurrentBag<AMQPQueueMetric> busyQueues, ConcurrentBag<AMQPQueueMetric> quietQueues, int percentageDifference) { var percentageChange = PercentageChangeCalculator.Calculate(current.ConsumptionRate, previous.ConsumptionRate); if (percentageChange <= -percentageDifference) { current.AMQPQueueMetricAnalysisResult = AMQPQueueMetricAnalysisResult.ConsumptionRateDecreased; quietQueues.Add(current); } else if (current.ConsumptionRate.Equals(0)) { current.AMQPQueueMetricAnalysisResult = AMQPQueueMetricAnalysisResult.ConsumptionRateZero; quietQueues.Add(current); } else analyser.Analyse(current, previous, busyQueues, quietQueues, percentageDifference); }
public IValidationResult Validate(IExcelLoader excelLoader, IDictionary<string, object> context) { if (excelLoader == null) throw new ArgumentNullException("excelLoader"); var messages = new ConcurrentBag<IValidationMessage>(); var result = new ValidationResult {ValidationTarget = excelLoader, Messages = messages }; var contextDic = context ?? new Dictionary<string, object>(); try { using (var cts = new CancellationTokenSource()) { _rules.AsParallel() .WithCancellation(cts.Token) .ForAll(r => { var ruleResult = r.Check(excelLoader, contextDic); foreach (var msg in ruleResult.Messages) { messages.Add(msg); } if (_earlyExit && !ruleResult.ShouldContinue) { cts.Cancel(); } }); } } catch (AggregateException ex) { var errors = ex.Flatten() .InnerExceptions .Select(x => x.ToString().ToValidationError()); foreach (var error in errors) { messages.Add(error); } } catch (OperationCanceledException) { // Intentionally swallow this exception. } catch (Exception ex) { var error = ex.ToString().ToValidationError(); messages.Add(error); } return result; }
public void Run() { var bag = new ConcurrentBag<int>(); Task.Run(() => { bag.Add(42); Thread.Sleep(1000); bag.Add(21); }); Task.Run(() => { foreach (int i in bag) Console.WriteLine(i); }).Wait(); }
private void Collect() { // if there are more than 10 tasks, let's clean it up. if(_tasks.Count > 10) { // create a new bag. var newtasks = new ConcurrentBag<Task>(); var oldTasks = _tasks; newtasks.Add(Task.Run(() => { // copy items over from the old bag that are still running. foreach(var t in oldTasks.Where(each => !each.IsCompleted)) { newtasks.Add(t); } })); // use the new bag from here on. _tasks = newtasks; } }
public IEnumerable<INews> FirstNews() { var newsInstance = InterNewsBL.Instance; var newsList = new ConcurrentBag<INews>(); try { var result = newsInstance.SelectTopNews(); result.AsParallel().AsOrdered().ForAll(val => { newsList.Add(new News { NewsID = val.NewsID, DisplayOrder = val.DisplayOrder, Heading = val.Heading, ImageUrl = val.ImageUrl, ShortDesc = val.ShortDescription, IsRss = val.IsRss, //NewsDesc= val.NewsDescription, DttmCreated = val.DttmCreated }); }); } catch (Exception) { throw; } finally { newsInstance.Dispose(); } return newsList.OrderByDescending(v => v.DttmCreated); }
public void ShouldBeUnique() { var generatedIds = new ConcurrentBag<Guid>(); var tasks = new List<Task>(); var i = Count; while (i-- > 0) { tasks.Add( Task.Factory.StartNew( () => { for (var j = 0; j < 100; j++) { var id = SeqGuid.NewGuid(); generatedIds.Add(id); } })); } Task.WaitAll(tasks.ToArray()); Assert.That(new HashSet<Guid>(generatedIds).Count, Is.EqualTo(Count * 100)); }
protected override IEnumerable<Achievement> GetUnlockedAchievements(StatisAnalysisSession statisAnalysisSession, IEnumerable<Achievement> availableAchievements) { var unlockedAchievements = new ConcurrentBag<Achievement>(); var tasks = new Task[availableAchievements.Count()]; var i = 0; foreach (var uncompletedAchievement in availableAchievements) { var a = uncompletedAchievement; tasks[i++] = Task.Factory.StartNew(() => { /* Technically we create a lot of objects all the time. * It's possible that these objects could have a lifespan longer than just a session. * However maintaining state is always a PITA */ var achievement = (StaticAnalysisAchievementBase)Activator.CreateInstance(a.AchievementType); if (achievement.IsAchievementUnlocked(statisAnalysisSession)) { a.CodeOrigin = achievement.AchievementCodeOrigin; a.IsCompleted = true; unlockedAchievements.Add(a); } }); } Task.WaitAll(tasks); return unlockedAchievements; }
public void SetUp() { Clock.Reset(); disposables = new CompositeDisposable { Disposable.Create(Clock.Reset) }; schedule = GetScheduleDelegate(); commandsScheduled = new ConcurrentBag<IScheduledCommand>(); commandsDelivered = new ConcurrentBag<IScheduledCommand>(); var configuration = new Configuration() .TraceScheduledCommands() // trace to console .TraceScheduledCommands( onScheduling: _ => { }, onScheduled: c => commandsScheduled.Add(c), onDelivering: _ => { }, onDelivered: c => commandsDelivered.Add(c)); Configure(configuration, d => disposables.Add(d)); disposables.Add(ConfigurationContext.Establish(configuration)); }
public override void ExecuteTests() { int verticesAmt = 20; var qualityVar = new ConcurrentBag<Tuple<double[], double[]>>(); Parallel.For(1, 10, aw10 => { double aW = (double)aw10 / 10; for (double rW = 0.1; rW < 1; rW += 0.1) { for (double k = 0.1; k < 1; k += 0.1) { Vertex[] vertices = base.GenerateVertices(verticesAmt); // The amount of UpdateForces iterations for (int i = 0; i < 1000; i++) vertices = UpdateForces(verticesAmt, vertices, aW, rW, k); // And put the quality of the graph into a Tuple along with its a and r weights var outTuple = new Tuple<double[], double[]>(new[] { aW, rW, k }, QualityTest.TestAll(vertices)); qualityVar.Add(outTuple); // Store the Graph in a file with the parameters Save.SaveGraph(new[] { aW, rW, k }, vertices); } } }); // Save the string array into a file Save.SaveStrings(GetQualitiesStrings(qualityVar)); }
public IEnumerable<IDocument> Execute(IReadOnlyList<IDocument> inputs, IExecutionContext context) { // Get syntax trees (supply path so that XML doc includes can be resolved) ConcurrentBag<SyntaxTree> syntaxTrees = new ConcurrentBag<SyntaxTree>(); Parallel.ForEach(inputs, input => { using (Stream stream = input.GetStream()) { SourceText sourceText = SourceText.From(stream); syntaxTrees.Add(CSharpSyntaxTree.ParseText(sourceText, path: input.String(Keys.SourceFilePath, string.Empty))); } }); // Create the compilation (have to supply an XmlReferenceResolver to handle include XML doc comments) MetadataReference mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location); CSharpCompilation compilation = CSharpCompilation .Create("CodeAnalysisModule", syntaxTrees) .WithReferences(mscorlib) .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, xmlReferenceResolver: new XmlFileResolver(context.InputFolder))); // Get and return the document tree AnalyzeSymbolVisitor visitor = new AnalyzeSymbolVisitor(context, _symbolPredicate, _writePath ?? (x => DefaultWritePath(x, _writePathPrefix)), _cssClasses, _docsForImplicitSymbols); visitor.Visit(compilation.Assembly.GlobalNamespace); return visitor.Finish(); }
public void Instance_ThreadSafe() { using (var gate = new Barrier(5)) { var result = new ConcurrentBag<AnyConstructorFinder>(); Action test = () => { gate.SignalAndWait(20); var instance = AnyConstructorFinder.Instance; Thread.MemoryBarrier(); result.Add(instance); }; var cycleState = Parallel.For(0, 200, new ParallelOptions { MaxDegreeOfParallelism = 15 }, x => { test(); }) ; while (!cycleState.IsCompleted) { Thread.Sleep(100); } Assert.IsTrue(result.All(x => x != null)); Assert.IsTrue(result.Distinct().Count() == 1); } }
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(); }
public void PopAndPush_CallPopBeforePush_CorrectCouners() { ConcurentQueue<int> concurentQueue = new ConcurentQueue<int>(10000); ConcurrentBag<int> popResult = new ConcurrentBag<int>(); ConcurrentBag<Exception> popResultEx = new ConcurrentBag<Exception>(); ConcurrentBag<int> pushItems = new ConcurrentBag<int>(); Parallel.For(0, 10, i => { pushItems.Add(i); try { var temp = concurentQueue.Pop(); popResult.Add(temp); } catch (Exception exp) { popResultEx.Add(exp); } concurentQueue.Push(i); }); Exception exception; popResultEx.TryPeek(out exception); Assert.IsInstanceOf(typeof(TimeoutException), exception); Assert.AreEqual(pushItems.Count, popResult.Count + popResultEx.Count); }
public async Task ItHasBeenFixed() { var activator = new BuiltinHandlerActivator(); Using(activator); var receivedMessageIds = new ConcurrentBag<string>(); activator.Handle<string>(async (_, context, message) => { receivedMessageIds.Add(context.TransportMessage.Headers[Headers.MessageId]); }); var bus = Configure.With(activator) .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "buggerino")) .Start(); var customHeaders = new Dictionary<string, string> { {"custom-header", "woohoo"} }; const string repeatedMessage = "hej med dig"; await bus.SendLocal(repeatedMessage, customHeaders); await bus.SendLocal("hej igen med", customHeaders); await bus.SendLocal(repeatedMessage, customHeaders); await Task.Delay(TimeSpan.FromSeconds(1)); Assert.That(receivedMessageIds.Distinct().Count(), Is.EqualTo(3), "Expected three unique message IDs - got: {0}", string.Join(", ", receivedMessageIds)); }
public void PopAndPush_CallPushBeforePop_CorrectCounters() { ConcurentQueue<int> concurentQueue = new ConcurentQueue<int>(10000); ConcurrentBag<int> popResult = new ConcurrentBag<int>(); ConcurrentBag<Exception> popResultEx = new ConcurrentBag<Exception>(); ConcurrentBag<int> pushItems = new ConcurrentBag<int>(); Parallel.For(0, 10, i => { concurentQueue.Push(i); }); Parallel.For(0, 10, i => { pushItems.Add(i); try { var temp = concurentQueue.Pop(); popResult.Add(temp); } catch (Exception Exp) { popResultEx.Add(Exp); } }); Assert.AreEqual(pushItems.Count, popResult.Count + popResultEx.Count + concurentQueue.Count); }
public async Task HandleFileUploaded(int fileIndex, string fileName, long fileSize, string fileType, long fileLastModified, int responseStatus, string responseText) { var fileUploaded = new FileUploadedEventArgs() { FileIndex = fileIndex, OriginalFileName = fileName, ContentType = fileType, Size = fileSize, LastModified = DateTimeOffset.FromUnixTimeMilliseconds(fileLastModified), ResponseStatus = (HttpStatusCode)responseStatus, ResponseText = responseText, }; filesUploaded?.Add(fileUploaded); await InvokeOnFileUploadedAsync(fileUploaded); }
public override object ProvideValue(IServiceProvider serviceProvider) { var target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget)); if (target == null) { throw new InvalidOperationException("Invalid method binding target"); } var eventInfo = target.TargetProperty as EventInfo; if (eventInfo == null) { throw new InvalidOperationException("The target property of the method binding must be an event"); } var targetDependencyObject = target.TargetObject as DependencyObject; if (!(targetDependencyObject is FrameworkElement) && !(targetDependencyObject is FrameworkContentElement)) { throw new InvalidOperationException("The method binding target must be a FrameworkElement or a FrameworkContentElement"); } // ReSharper disable AssignNullToNotNullAttribute object dataContext = targetDependencyObject.GetValue(FrameworkElement.DataContextProperty) ?? targetDependencyObject.GetValue(FrameworkContentElement.DataContextProperty); // ReSharper restore AssignNullToNotNullAttribute if (dataContext == null) { throw new InvalidOperationException("No DataContext found on method binding target"); } object handler = GetHandler(dataContext, eventInfo, MethodName); if (handler == null) { throw new ArgumentException("No valid instance parameterless method with the specified name that returns void was found for method binding.", nameof(MethodName)); } #if DEBUG // ReSharper disable AssignNullToNotNullAttribute EventBindingStore?.Add(new Tuple <DependencyObject, string, object, string>(targetDependencyObject, eventInfo.Name, dataContext, MethodName)); // ReSharper restore AssignNullToNotNullAttribute #endif return(handler); }
private void PrecompileLibrary(ITaskItem assemblyItem) { string assembly = assemblyItem.ItemSpec; string directory = Path.GetDirectoryName(assembly) !; var aotAssembly = new TaskItem(assembly); var aotArgs = new List <string>(); var processArgs = new List <string>(); var a = assemblyItem.GetMetadata("AotArguments"); if (a != null) { aotArgs.AddRange(a.Split(";", StringSplitOptions.RemoveEmptyEntries)); } var p = assemblyItem.GetMetadata("ProcessArguments"); if (p != null) { processArgs.AddRange(p.Split(";", StringSplitOptions.RemoveEmptyEntries)); } Utils.LogInfo($"[AOT] {assembly}"); processArgs.Add("--debug"); // add LLVM options if (UseLLVM) { processArgs.Add("--llvm"); aotArgs.Add($"nodebug"); // can't use debug symbols with LLVM aotArgs.Add($"llvm-path={LLVMPath}"); } else { processArgs.Add("--nollvm"); } // compute output mode and file names if (parsedAotMode == MonoAotMode.LLVMOnly) { aotArgs.Add("llvmonly"); string llvmBitcodeFile = Path.ChangeExtension(assembly, ".dll.bc"); aotArgs.Add($"outfile={llvmBitcodeFile}"); aotAssembly.SetMetadata("LlvmBitcodeFile", llvmBitcodeFile); } else { if (parsedAotMode == MonoAotMode.Full) { aotArgs.Add("full"); } if (parsedOutputType == MonoAotOutputType.AsmOnly) { aotArgs.Add("asmonly"); string assemblerFile = Path.ChangeExtension(assembly, ".dll.s"); aotArgs.Add($"outfile={assemblerFile}"); aotAssembly.SetMetadata("AssemblerFile", assemblerFile); } else { string objectFile = Path.ChangeExtension(assembly, ".dll.o"); aotArgs.Add($"outfile={objectFile}"); aotAssembly.SetMetadata("ObjectFile", objectFile); } if (UseLLVM) { string llvmObjectFile = Path.ChangeExtension(assembly, ".dll-llvm.o"); aotArgs.Add($"llvm-outfile={llvmObjectFile}"); aotAssembly.SetMetadata("LlvmObjectFile", llvmObjectFile); } } // pass msym-dir if specified if (MsymPath != null) { aotArgs.Add($"msym-dir={MsymPath}"); } string aotDataFile = Path.ChangeExtension(assembly, ".aotdata"); aotArgs.Add($"data-outfile={aotDataFile}"); aotAssembly.SetMetadata("AotDataFile", aotDataFile); // we need to quote the entire --aot arguments here to make sure it is parsed // on Windows as one argument. Otherwise it will be split up into multiple // values, which wont work. processArgs.Add($"\"--aot={String.Join(",", aotArgs)}\""); processArgs.Add(assembly); var envVariables = new Dictionary <string, string> { { "MONO_PATH", directory }, { "MONO_ENV_OPTIONS", String.Empty } // we do not want options to be provided out of band to the cross compilers }; // run the AOT compiler Utils.RunProcess(CompilerBinaryPath, String.Join(" ", processArgs), envVariables, directory); compiledAssemblies.Add(aotAssembly); }
private void WriteFileComponentContent(XmlWriter xmlWriter, FeedGenerationFileLineItem fileComponent, IDataReader reader, string identifier, ref Tuple <int, int, int> countRec) { var attributesDictionary = ConfigurationManager.GetSection(fileComponent.Catalogattributesection) as StringDictionary; if (countRec == null) { throw new ArgumentNullException("countRec"); } var countProcessed = 0; var countDeleted = 0; var countError = 0; //<entry> while (reader.Read()) { Log.DebugFormat("{0}::Processing record [{1}]: {2}", identifier, (countProcessed + countError + countDeleted), reader["PID"]); var id = reader[attributesDictionary["gId"]].ToString(); var title = reader[attributesDictionary["title"]].ToString(); try { var haveRulesChanged = _runnerHelper.HaveRulesChanged; var linkSku = reader[attributesDictionary["linkSku"]].ToString(); var brandName = !attributesDictionary.ContainsKey("gBrand") ? string.Empty : reader[attributesDictionary["gBrand"]].ToString(); var cContributors = GetContributors(attributesDictionary, reader); // Get the breadcrumb value var defaultCategory = FeedUtils.GetFeedGeneratorIndigoCategory(_feedGeneratorCategoryService, reader, attributesDictionary, fileComponent.Catalog, Log); var productData = FeedUtils.GetProductData(attributesDictionary, reader, linkSku, fileComponent.Catalog, brandName, cContributors, defaultCategory); var sanitizedTitle = (string.IsNullOrWhiteSpace(title)) ? string.Empty : FeedUtils.SanitizeString(title); var gAvailability = !attributesDictionary.ContainsKey("gAvailability") ? FeedUtils.GetGoogleAvailability(1) : FeedUtils.GetGoogleAvailability((int)reader[attributesDictionary["gAvailability"]]); var availability = !attributesDictionary.ContainsKey("gAvailability") ? 1 : (int)reader[attributesDictionary["gAvailability"]]; var recordType = !attributesDictionary.ContainsKey("recordType") ? string.Empty : reader[attributesDictionary["recordType"]].ToString(); var merchandiseType = !attributesDictionary.ContainsKey("merchandiseType") ? string.Empty : reader[attributesDictionary["merchandiseType"]].ToString(); if (string.IsNullOrWhiteSpace(merchandiseType)) { _missingMerchandiseTypeProductInfos.Add(new MissingMerchandiseTypeProductInfo { Breadcrumb = defaultCategory.Breadcrumb, Sku = linkSku, Title = sanitizedTitle }); } IRuleEvaluationResult newZeroCommissionResult = null; IRuleEvaluationResult newPromotionalTextResult = null; if (_isIncrementalRun) { var isModifiedData = int.Parse(reader["IsModified"].ToString()); if (isModifiedData == 0) { if (!haveRulesChanged) { Log.DebugFormat( "Product with pid {0} is skipped in incremental mode as it wasn't modified and the rules haven't changed.", id); continue; } var oldZeroCommissionResult = _runnerHelper.GetZeroCommissionRuleResult(productData, true); newZeroCommissionResult = _runnerHelper.GetZeroCommissionRuleResult(productData, false); var oldPromotionalTextResult = _runnerHelper.GetPromotionalTextRuleResult(productData, true); newPromotionalTextResult = _runnerHelper.GetPromotionalTextRuleResult(productData, false); if (oldZeroCommissionResult.HasMatch == newZeroCommissionResult.HasMatch && oldPromotionalTextResult.HasMatch == newPromotionalTextResult.HasMatch && oldPromotionalTextResult.MatchingRulePayLoads.First() .Equals(newPromotionalTextResult.MatchingRulePayLoads.First())) { countDeleted++; Log.DebugFormat( "Product with pid {0} is skipped in incremental mode as it wasn't modified and rule evaluations yielded same results.", id); continue; } // At this point, we know that rules have changed, which means we need to resend this product as modified } else { newZeroCommissionResult = _runnerHelper.GetZeroCommissionRuleResult(productData, false); newPromotionalTextResult = _runnerHelper.GetPromotionalTextRuleResult(productData, false); } } else { newZeroCommissionResult = _runnerHelper.GetZeroCommissionRuleResult(productData, false); newPromotionalTextResult = _runnerHelper.GetPromotionalTextRuleResult(productData, false); } var isZeroCommissionElement = newZeroCommissionResult.HasMatch || IsZeroCommissionElement(sanitizedTitle, _feedId, true, availability, recordType); if (isZeroCommissionElement) { Log.DebugFormat("Product with pid {0} is being placed in zero commission list due to either data issues or zero commission rules.)", id); } var linkCatalog = attributesDictionary["linkCatalog"]; if (string.IsNullOrWhiteSpace(sanitizedTitle)) { sanitizedTitle = "(No Title)"; } var description = reader[attributesDictionary["description"]].ToString(); description = string.IsNullOrWhiteSpace(description) ? sanitizedTitle : FeedUtils.SanitizeString(description); // Get the breadcrumb value var breadcrumb = defaultCategory.Breadcrumb; var gPrice = string.IsNullOrEmpty(attributesDictionary["price"]) ? "" : reader[attributesDictionary["price"]].ToString(); var gAdjustedPrice = string.IsNullOrEmpty(attributesDictionary["adjustedPrice"]) ? string.Empty : reader[attributesDictionary["adjustedPrice"]].ToString(); var publisherName = !attributesDictionary.ContainsKey("publisherName") ? string.Empty : reader[attributesDictionary["publisherName"]].ToString(); if (!string.IsNullOrWhiteSpace(recordType) && recordType.Equals("GCard_Electronic", StringComparison.OrdinalIgnoreCase)) { gPrice = DefaultEGiftCardPrice; gAdjustedPrice = DefaultEGiftCardPrice; } var entry = EntryAttribute(fileComponent.Catalog, reader, attributesDictionary , id , sanitizedTitle , linkCatalog, linkSku , gPrice , gAdjustedPrice , gAvailability , brandName, publisherName, cContributors, breadcrumb, isZeroCommissionElement, merchandiseType, newPromotionalTextResult, description); countProcessed++; //out of memory exception will be thrown if we keep the xml entries in memory entry.WriteTo(xmlWriter); } catch (Exception e) { countError++; Log.ErrorFormat("Can't process the item. Id:{0};title:{1}", id, title); Log.DebugFormat("Error stack trace: {0}", e); _executionLogLogger.AddCustomMessage(string.Format("Can't process the item. Id: {0};title: {1}, file identifier: {2}", id, title, identifier)); if (!AllowItemErrorsInFiles || _isIncrementalRun) { _hasError = true; } } } // Now process the deleted items for the range & producttypeid and put them in the xml file as "deleted" items if (_isIncrementalRun) { // Don't do it for gift card file component if (!fileComponent.StoredProcedureName.Equals("uspCJFeedGeneralMerchandiseGiftCard", StringComparison.OrdinalIgnoreCase)) { foreach (var deletedProductInfo in GetDeletedProductInfos(identifier)) { GetDeletedElement(deletedProductInfo).WriteTo(xmlWriter); countDeleted++; } } } Log.InfoFormat("{0} completed. Processed record count: {1}, Error record count: {2}, deleted/skipped record count {3}", identifier, countProcessed, countError, countDeleted); countRec = new Tuple <int, int, int>(countRec.Item1 + countProcessed, countRec.Item2 + countError, countRec.Item3 + countDeleted); }
public static ConcurrentBag <MyGroups <MyCubeGrid, MyGridMechanicalGroupData> .Group> FindLookAtGridGroupMechanical(IMyCharacter controlledEntity) { try { const float range = 5000; Matrix worldMatrix; Vector3D startPosition; Vector3D endPosition; worldMatrix = controlledEntity.GetHeadMatrix(true, true, false); // dead center of player cross hairs, or the direction the player is looking with ALT. startPosition = worldMatrix.Translation + worldMatrix.Forward * 0.5f; endPosition = worldMatrix.Translation + worldMatrix.Forward * (range + 0.5f); var list = new Dictionary <MyGroups <MyCubeGrid, MyGridMechanicalGroupData> .Group, double>(); var ray = new RayD(startPosition, worldMatrix.Forward); foreach (var group in MyCubeGridGroups.Static.Mechanical.Groups) { foreach (MyGroups <MyCubeGrid, MyGridMechanicalGroupData> .Node groupNodes in group.Nodes) { MyCubeGrid cubeGrid = groupNodes.NodeData; if (cubeGrid != null) { if (cubeGrid.MarkedForClose || cubeGrid.MarkedAsTrash || !cubeGrid.InScene) { continue; } // check if the ray comes anywhere near the Grid before continuing. if (ray.Intersects(cubeGrid.PositionComp.WorldAABB).HasValue) { Vector3I?hit = cubeGrid.RayCastBlocks(startPosition, endPosition); if (hit.HasValue) { double distance = (startPosition - cubeGrid.GridIntegerToWorld(hit.Value)).Length(); if (list.TryGetValue(group, out double oldDistance)) { if (distance < oldDistance) { list.Remove(group); list.Add(group, distance); } } else { list.Add(group, distance); } } } } } } ConcurrentBag <MyGroups <MyCubeGrid, MyGridMechanicalGroupData> .Group> bag = new ConcurrentBag <MyGroups <MyCubeGrid, MyGridMechanicalGroupData> .Group>(); if (list.Count == 0) { return(bag); } // find the closest Entity. var item = list.OrderBy(f => f.Value).First(); bag.Add(item.Key); return(bag); } catch (Exception e) { //Hangar.Debug("Matrix Error!", e, Hangar.ErrorType.Trace); return(null); } }
public void AddRule(IRule rule) { _rules.Add(rule); }
public void DCAwareRoundRobinPolicyTestInParallel() { var hostList = new List <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") }; var localHostsLength = hostList.Count(h => h.Datacenter == "dc1"); const string localDc = "dc1"; var clusterMock = new Mock <ICluster>(); clusterMock .Setup(c => c.AllHosts()) .Returns(hostList); //Initialize the balancing policy var policy = new DCAwareRoundRobinPolicy(localDc, 1); policy.Initialize(clusterMock.Object); var allHosts = new ConcurrentBag <Host>(); var firstHosts = new ConcurrentBag <Host>(); Action action = () => { var hosts = policy.NewQueryPlan(null, null).ToList(); //Check that the value is not repeated Assert.AreEqual(0, hosts.GroupBy(x => x) .Where(g => g.Count() > 1) .Select(y => y.Key) .Count()); firstHosts.Add(hosts[0]); //Add to the general list foreach (var h in hosts) { allHosts.Add(h); } }; var actions = new List <Action>(); const int times = 100; for (var i = 0; i < times; i++) { actions.Add(action); } TestHelper.ParallelInvoke(actions); //Check that the first nodes where different foreach (var h in hostList) { if (h.Datacenter == localDc) { Assert.AreEqual(times / localHostsLength, firstHosts.Count(hc => hc == h)); } else { Assert.AreEqual(0, firstHosts.Count(hc => hc == h)); } } clusterMock.Verify(); }
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))); }
public void TokenAwarePolicyRoundRobinsOnLocalReplicas() { var hostList = new List <Host> { //5 local nodes and 4 remote TestHelper.CreateHost("0.0.0.1", "dc1"), TestHelper.CreateHost("0.0.0.2", "dc1"), TestHelper.CreateHost("0.0.0.3", "dc2"), TestHelper.CreateHost("0.0.0.4", "dc2"), TestHelper.CreateHost("0.0.0.5", "dc1"), TestHelper.CreateHost("0.0.0.6", "dc1"), TestHelper.CreateHost("0.0.0.7", "dc2"), TestHelper.CreateHost("0.0.0.8", "dc2"), TestHelper.CreateHost("0.0.0.9", "dc1") }; var clusterMock = new Mock <ICluster>(MockBehavior.Strict); clusterMock .Setup(c => c.AllHosts()) .Returns(hostList) .Verifiable(); clusterMock .Setup(c => c.GetReplicas(It.IsAny <string>(), It.IsAny <byte[]>())) .Returns <string, byte[]>((keyspace, key) => { var i = key[0]; return(hostList.Where(h => { //The host at with address == k and the next one var address = TestHelper.GetLastAddressByte(h); return address == i || address == i + 1; }).ToList()); }) .Verifiable(); var policy = new TokenAwarePolicy(new DCAwareRoundRobinPolicy("dc1", 2)); policy.Initialize(clusterMock.Object); var firstHosts = new ConcurrentBag <Host>(); var k = new RoutingKey { RawRoutingKey = new byte[] { 1 } }; // key for host :::1 and :::2 const int times = 10000; Action action = () => { var h = policy.NewQueryPlan(null, new SimpleStatement().SetRoutingKey(k)).First(); firstHosts.Add(h); }; TestHelper.ParallelInvoke(action, times); Assert.AreEqual(times, firstHosts.Count); double queryPlansWithHost1AsFirst = firstHosts.Count(h => TestHelper.GetLastAddressByte(h) == 1); double queryPlansWithHost2AsFirst = firstHosts.Count(h => TestHelper.GetLastAddressByte(h) == 2); Assert.AreEqual(times, queryPlansWithHost1AsFirst + queryPlansWithHost2AsFirst); // Around half will to one and half to the other Assert.That(queryPlansWithHost1AsFirst / times, Is.GreaterThan(0.48).And.LessThan(0.52)); Assert.That(queryPlansWithHost2AsFirst / times, Is.GreaterThan(0.48).And.LessThan(0.52)); clusterMock.Verify(); }
private IAnalysisSet AddReference(Node node, Func <string, ObjectHandle> partialLoader) { // processes a call to clr.AddReference updating project state // so that it contains the newly loaded assembly. var callExpr = node as CallExpression; if (callExpr == null) { return(AnalysisSet.Empty); } foreach (var arg in callExpr.Args) { var cexpr = arg.Expression as Microsoft.PythonTools.Parsing.Ast.ConstantExpression; if (cexpr == null || !(cexpr.Value is string || cexpr.Value is AsciiString)) { // can't process this add reference continue; } // TODO: Should we do a .NET reflection only load rather than // relying on the CLR module here? That would prevent any code from // running although at least we don't taint our own modules which // are loaded with this current code. var asmName = cexpr.Value as string; if (asmName == null) { // check for byte string var bytes = cexpr.Value as AsciiString; if (bytes != null) { asmName = bytes.String; } } if (asmName != null && !_assemblyLoadSet.Contains(asmName)) { _assemblyLoadSet.Add(asmName); ObjectHandle asm = null; try { if (partialLoader != null) { asm = partialLoader(asmName); } else { try { asm = LoadAssemblyByName(asmName); } catch { asm = null; } if (asm == null) { asm = LoadAssemblyByPartialName(asmName); } } if (asm == null && _state != null) { foreach (var dir in _state.AnalysisDirectories) { if (!PathUtils.IsValidPath(dir) && !PathUtils.IsValidPath(asmName)) { string path = Path.Combine(dir, asmName); if (File.Exists(path)) { asm = Remote.LoadAssemblyFrom(path); } else if (File.Exists(path + ".dll")) { asm = Remote.LoadAssemblyFrom(path + ".dll"); } else if (File.Exists(path + ".exe")) { asm = Remote.LoadAssemblyFrom(path + ".exe"); } } } } } catch { } if (asm != null && Remote.AddAssembly(asm)) { RaiseModuleNamesChanged(); } } } return(AnalysisSet.Empty); }
public bool Run(IList <string> folders, IList <string> files) { var cancellation = new CancellationTokenSource(); _cancel = cancellation.Token; using (var task = Task.Factory.StartNew(() => { // do folders (parallel) if (folders.Count > 0) { //! do not use aggregation, see file remarks Parallel.ForEach(folders, new ParallelOptions() { CancellationToken = _cancel }, folder => { Check(); _Result.Add(new FolderItem() { Name = Path.GetFileName(folder), Size = CalculateFolderSize(folder) }); _progress.SetProgressValue(_Result.Count, folders.Count); }); } Check(); // do files (serial) if (files.Count > 0) { _progress.Activity = "Computing file sizes"; foreach (var file in files) { try { var info = new FileInfo(file); _Result.Add(new FolderItem() { Name = info.Name, Size = info.Length }); } catch (Exception ex) { _Errors.Add(ex); } } } Check(); // done _progress.Complete(); }, _cancel)) { if (!task.Wait(750)) { _progress.Title = "Computing sizes"; _progress.Canceled += delegate { cancellation.Cancel(true); }; _progress.CanCancel = true; _progress.Show(); } try { task.Wait(); } catch (AggregateException) { } return(task.Status == TaskStatus.RanToCompletion); } }
private static Task PublishAsync(object @event, ConcurrentBag <CelebrityEventBase> bag) { bag.Add(@event as CelebrityEventBase); return(Task.CompletedTask); }
public Task <bool> RegisterUser(UserModel userModel) { _userStore.Add(userModel); return(Task.FromResult(true)); }
/// <summary> /// 写入一条秘密消息,轮到玩家出牌时才能看到。 /// </summary> /// <param name="message">秘密消息</param> public void WriteSecretMessage(GameMessage message) { secretMessages.Add(message); }
public async Task WorkLoopAsyncTest(int throttle, bool singleLoop) { // Arrange var testQueue = new ConcurrentQueue <WorkItem>(); var completedWork = new ConcurrentBag <WorkItem>(); var defaultItems = GenFu.GenFu.ListOf <WorkItem>(); defaultItems.ForEach(x => { x.Queue = "default"; testQueue.Enqueue(x); }); var primaryItems = GenFu.GenFu.ListOf <WorkItem>(); primaryItems.ForEach(x => { x.Queue = "primary"; testQueue.Enqueue(x); }); var secondaryItems = GenFu.GenFu.ListOf <WorkItem>(); secondaryItems.ForEach(x => { x.Queue = "secondary"; testQueue.Enqueue(x); }); _quidjiboConfiguration.EnableWorker.Returns(true); _quidjiboConfiguration.Throttle.Returns(throttle); _quidjiboConfiguration.LockInterval.Returns(60); _quidjiboConfiguration.SingleLoop.Returns(singleLoop); _quidjiboConfiguration.Queues.Returns(new[] { "default", "primary", "secondary" }); _workProvider.ReceiveAsync(Arg.Any <string>(), Arg.Any <CancellationToken>()) .Returns(x => testQueue.TryDequeue(out var item) ? Task.FromResult(new List <WorkItem> { item }) : Task.FromResult(new List <WorkItem>(0))); _workProvider.RenewAsync(Arg.Any <WorkItem>(), Arg.Any <CancellationToken>()).Returns(Task.FromResult(DateTime.UtcNow.AddMinutes(1))); _workProvider.CompleteAsync(Arg.Any <WorkItem>(), Arg.Any <CancellationToken>()) .Returns(x => { completedWork.Add(x.Arg <WorkItem>()); return(Task.CompletedTask); }); // Act _sut.Start(); // Assert while (!testQueue.IsEmpty && !_cts.IsCancellationRequested) { } testQueue.Count.Should().Be(0); if (singleLoop) { await _workProviderFactory.Received(1).CreateAsync(Arg.Any <string>(), Arg.Any <CancellationToken>()); } else { await _workProviderFactory.Received(1).CreateAsync(Arg.Is <string>(x => x == "default"), Arg.Any <CancellationToken>()); await _workProviderFactory.Received(1).CreateAsync(Arg.Is <string>(x => x == "primary"), Arg.Any <CancellationToken>()); await _workProviderFactory.Received(1).CreateAsync(Arg.Is <string>(x => x == "secondary"), Arg.Any <CancellationToken>()); } await _pipeline.ReceivedWithAnyArgs(75).StartAsync(Arg.Any <IQuidjiboContext>(), Arg.Any <CancellationToken>()); }
public static void Slicing() { using (Benchmark b = new Benchmark("Dumb way to attack")) { Console.WriteLine("This is dumb"); int[] items = Enumerable.Range(0, 5000000).ToArray(); List <int> primes = new List <int>(); foreach (var v in items) { if (Primes.isPrime(v)) { primes.Add(v); } } //Console.WriteLine(primes.PrettyPrint()); Console.WriteLine("Count is :" + primes.ToList().Count.ToString()); } Console.WriteLine("Press anykey to continue..."); Console.ReadLine(); using (Benchmark b = new Benchmark("Also Dumb way to attack")) { List <int> primes = new List <int>(); try { Console.WriteLine("This is even dumber"); int[] items = Enumerable.Range(0, 5000000).ToArray(); Parallel.ForEach(items, v => { if (Primes.isPrime(v)) { primes.Add(v); } }); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } //Console.WriteLine(primes.PrettyPrint()); Console.WriteLine("Count is :" + primes.ToList().Count.ToString()); } Console.WriteLine("Press anykey to continue..."); Console.ReadLine(); using (Benchmark b = new Benchmark("Behold the power of parallel and a concurrent data structure")) { ConcurrentBag <int> primes = new ConcurrentBag <int>(); try { Console.WriteLine("This is smarter"); int[] items = Enumerable.Range(0, 5000000).ToArray(); Parallel.ForEach(items, v => { if (Primes.isPrime(v)) { primes.Add(v); } }); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } //Console.WriteLine(primes.ToList().PrettyPrint()); Console.WriteLine("Count is :" + primes.ToList().Count.ToString()); } Console.WriteLine("Press anykey to continue..."); Console.ReadLine(); using (Benchmark b = new Benchmark("Behold the power of parallel and a non-concurrent data structure")) { int primeCount = 0; try { Console.WriteLine("Bad counting!"); int[] items = Enumerable.Range(0, 5000000).ToArray(); Parallel.ForEach(items, v => { if (Primes.isPrime(v)) { primeCount++; } }); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.WriteLine("Count is :" + primeCount.ToString()); } Console.WriteLine("Press anykey to continue..."); Console.ReadLine(); using (Benchmark b = new Benchmark("Behold the power of parallel and a non-concurrent data structure with Interlock")) { int primeCount = 0; try { Console.WriteLine("This is smarter"); int[] items = Enumerable.Range(0, 5000000).ToArray(); Parallel.ForEach(items, v => { if (Primes.isPrime(v)) { Interlocked.Increment(ref primeCount); } }); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.WriteLine("Count is :" + primeCount.ToString()); } Console.WriteLine("Press anykey to continue..."); Console.ReadLine(); }
/// <summary> /// Loads all of the players, stashes, and vaults. /// Shows a progress dialog. /// Used for the searching function. /// </summary> private void LoadAllFiles() { // Check to see if we failed the last time we tried loading all of the files. // If we did fail then turn it off and skip it. if (!Config.Settings.Default.LoadAllFilesCompleted) { if (MessageBox.Show( Resources.MainFormDisableLoadAllFiles, Resources.MainFormDisableLoadAllFilesCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, RightToLeftOptions) == DialogResult.Yes) { Config.Settings.Default.LoadAllFilesCompleted = true; Config.Settings.Default.LoadAllFiles = false; Config.Settings.Default.Save(); return; } } string[] vaults = GamePathResolver.GetVaultList(); var charactersIT = this.characterComboBox.Items.OfType <PlayerSave>().ToArray(); int numIT = charactersIT?.Length ?? 0; int numVaults = vaults?.Length ?? 0; // Since this takes a while, show a progress dialog box. int total = numIT + numVaults - 1; if (total > 0) { // We were successful last time so we reset the flag for this attempt. Config.Settings.Default.LoadAllFilesCompleted = false; Config.Settings.Default.Save(); } else { return; } Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); // Load all of the Immortal Throne player files and stashes. var bagPlayer = new ConcurrentBag <LoadPlayerResult>(); var bagPlayerStashes = new ConcurrentBag <LoadPlayerStashResult>(); var bagVault = new ConcurrentBag <LoadVaultResult>(); var lambdacharactersIT = charactersIT.Select(c => (Action)(() => { // Get the player var result = this.playerService.LoadPlayer(c, true); bagPlayer.Add(result); this.backgroundWorkerLoadAllFiles.ReportProgress(1); })).ToArray(); var lambdacharacterStashes = charactersIT.Select(c => (Action)(() => { // Get the player's stash var result = this.stashService.LoadPlayerStash(c); bagPlayerStashes.Add(result); this.backgroundWorkerLoadAllFiles.ReportProgress(1); })).ToArray(); var lambdaVault = vaults.Select(c => (Action)(() => { // Load all of the vaults. var result = this.vaultService.LoadVault(c); bagVault.Add(result); this.backgroundWorkerLoadAllFiles.ReportProgress(1); })).ToArray(); Parallel.Invoke(lambdacharactersIT.Concat(lambdacharacterStashes).Concat(lambdaVault).ToArray()); // Parallel loading // Dispay errors bagPlayer.Where(p => p.Player.ArgumentException != null).ToList() .ForEach(result => { if (result.Player.ArgumentException != null) { string msg = string.Format(CultureInfo.CurrentUICulture, "{0}\n{1}\n{2}", Resources.MainFormPlayerReadError, result.PlayerFile, result.Player.ArgumentException.Message); MessageBox.Show(msg, Resources.GlobalError, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, RightToLeftOptions); } }); bagPlayerStashes.Where(p => p.Stash.ArgumentException != null).ToList() .ForEach(result => { if (result.Stash.ArgumentException != null) { string msg = string.Format(CultureInfo.CurrentUICulture, "{0}\n{1}\n{2}", Resources.MainFormPlayerReadError, result.StashFile, result.Stash.ArgumentException.Message); MessageBox.Show(msg, Resources.GlobalError, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, RightToLeftOptions); } }); bagVault.Where(p => p.ArgumentException != null).ToList() .ForEach(result => { if (result.ArgumentException != null) { string msg = string.Format(CultureInfo.CurrentUICulture, "{0}\n{1}\n{2}", Resources.MainFormPlayerReadError, result.Filename, result.ArgumentException.Message); MessageBox.Show(msg, Resources.GlobalError, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, RightToLeftOptions); } }); stopWatch.Stop(); // Get the elapsed time as a TimeSpan value. TimeSpan ts = stopWatch.Elapsed; // Format and display the TimeSpan value. Log.LogInformation("LoadTime {0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); // We made it so set the flag to indicate we were successful. Config.Settings.Default.LoadAllFilesCompleted = true; Config.Settings.Default.Save(); }
public void Add(Product product) { _products.Add(product); }
/// <summary> /// Construct (partial) association rules. /// </summary> public void Generate() { ConcurrentBag <AssociationRule> result = new ConcurrentBag <AssociationRule>(); ConcurrentBag <Task> tasks = new ConcurrentBag <Task>(); ConcurrentBag <AlgorithmProgressExecution> algExecution = new ConcurrentBag <AlgorithmProgressExecution>(); int index = 0; foreach (Row singleRow in InformationSystem.Rows) { List <Attribute> attrs = singleRow.Attributes.Where(x => InformationSystem.DecisionAttributes[x.Name] == true).Select(x => x).ToList(); foreach (Attribute decisionAttribute in attrs) { var localCopy = System.Tuple.Create <Row, Attribute>(singleRow, decisionAttribute); Task <AssociationRule> task = Task.Factory.StartNew <AssociationRule>((variables) => { var decAttr = ((System.Tuple <Row, Attribute>)variables).Item2; var row = ((System.Tuple <Row, Attribute>)variables).Item1; #region algorithm body IList <Row> separatedRows = null; Condition decisionAttributeInResult = new Condition(decAttr); IList <Condition> conditions = new List <Condition>(); separatedRows = InformationSystem.Rows.GetRowsSeparatedByAttribute(row, decAttr); IList <Row> separatedRowsCopy = separatedRows; int alreadyCovered = 0; List <int> deltas = new List <int>(); int minimumNumberOfRowsToSeparate = System.Convert.ToInt32(System.Math .Ceiling((1 - InformationSystem.Alpha) * separatedRows.Count)); AlgorithmProgressExecution progress = new AlgorithmProgressExecution() { DecisionAttribute = decAttr }; while (alreadyCovered < minimumNumberOfRowsToSeparate) { AlgorithmIteration iteration = new AlgorithmIteration() { IterationNumber = progress.Iterations.Count() + 1, ObjectsToCover = separatedRowsCopy.Count }; IList <Subset> subsets = separatedRowsCopy.CreateSubsets(row, decAttr, false); string subsetWithMaxElements = subsets .OrderByDescending(x => x.Count) .Select(x => x.Name) .First(); int elementsQuantityInSelectedSubset = subsets.Where( x => x.Name == subsetWithMaxElements) .Select(x => x.Count) .First(); iteration.ObjectsCovered = elementsQuantityInSelectedSubset; deltas.Add(elementsQuantityInSelectedSubset); alreadyCovered += elementsQuantityInSelectedSubset; conditions.Add(new Condition(row.Attributes .Where(x => x.Name == subsetWithMaxElements).First())); separatedRowsCopy = separatedRowsCopy .RemoveElementsFromAlreadyCoveredSubsets (subsets, subsetWithMaxElements); progress.Iterations.Add(iteration); } var rule = new AssociationRule(conditions, decisionAttributeInResult); var supportAndConfidence = rule.CalculateSupportAndConfidence(InformationSystem.Rows); rule.Support = supportAndConfidence.Item1.Round(); rule.Confidence = supportAndConfidence.Item2.Round(); var upperLowerBound = rule.CalculateUpperAndLowerBound(minimumNumberOfRowsToSeparate, deltas); rule.UpperBound = upperLowerBound.Item1; rule.LowerBound = upperLowerBound.Item2; algExecution.Add(progress); #endregion return(rule); }, localCopy, CancellationToken.None, TaskCreationOptions.AttachedToParent, TaskScheduler.Default); task.ContinueWith(x => { if (x.Status == TaskStatus.RanToCompletion) { lock (locker) { result.Add(((Task <AssociationRule>)x).Result); Notify(++index); } } }, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, guiScheduler); tasks.Add(task); } } var finish = Task.Factory.ContinueWhenAll(tasks.ToArray(), x => { SeparatedRows(algExecution); Rules(result); }, CancellationToken.None, TaskContinuationOptions.None, guiScheduler); }
private static Task ConnectBatch(string url, string transport, int batchSize, ConcurrentBag <Connection> connections) { var options = new ParallelOptions { MaxDegreeOfParallelism = batchSize }; var batchTcs = new TaskCompletionSource <object>(); long remaining = batchSize; Parallel.For(0, batchSize, options, async i => { var connection = new Connection(url); if (!_running) { batchTcs.TrySetResult(null); return; } try { var clientTransport = GetTransport(transport); await(clientTransport == null ? connection.Start() : connection.Start(clientTransport)); if (_running) { connections.Add(connection); var clientId = connection.ConnectionId; connection.Error += e => { Debug.WriteLine(String.Format("SIGNALR: Client {0} ERROR: {1}", clientId, e)); }; connection.Closed += () => { Debug.WriteLine(String.Format("SIGNALR: Client {0} CLOSED", clientId)); // Remove it from the list on close connections.TryTake(out connection); }; } } catch (Exception ex) { Console.WriteLine("Failed to start client. {0}", ex.GetBaseException()); } finally { if (Interlocked.Decrement(ref remaining) == 0) { // When all connections are connected, mark the task as complete batchTcs.TrySetResult(null); } } }); return(batchTcs.Task); }
//public methods public void AddEvent(DateTime dt) { events.Add(dt); }
void ProcessReadbackRequests() { while (CaptureQueue.Count > 0) { var capture = CaptureQueue.Peek(); if (capture.Request.hasError) { CaptureQueue.Dequeue(); AvailableGpuDataArrays.Add(capture.GpuData); Debug.Log("Failed to read GPU texture"); } else if (capture.Request.done) { CaptureQueue.Dequeue(); if (Bridge != null && Bridge.Status == Status.Connected) { // TODO: Remove the following two lines of extra memory copy, when we can use // AsyncGPUReadback.RequestIntoNativeArray. var data = capture.Request.GetData <byte>(); NativeArray <byte> .Copy(data, capture.GpuData, data.Length); var imageData = new ImageData() { Name = Name, Frame = Frame, Width = Width, Height = Height, Sequence = Sequence, }; if (!JpegOutput.TryTake(out imageData.Bytes)) { imageData.Bytes = new byte[MaxJpegSize]; } Tasks.Enqueue(Task.Run(() => { imageData.Length = JpegEncoder.Encode(capture.GpuData, Width, Height, 4, JpegQuality, imageData.Bytes); if (imageData.Length > 0) { imageData.Time = capture.CaptureTime; ImageWriter.Write(imageData); } else { Debug.Log("Compressed image is empty, length = 0"); } JpegOutput.Add(imageData.Bytes); AvailableGpuDataArrays.Add(capture.GpuData); })); Sequence++; } else { AvailableGpuDataArrays.Add(capture.GpuData); } } else { break; } } }
public Task <Result <Customer> > CreateAsync(Customer customer) { _customers.Add(customer); return(Task.FromResult(Result <Customer> .Success(customer))); }
public void TestServiceBusWithRemoteKafka() { IServiceBus serviceBus = ServiceBus.Configure() .WithKafkaEndpoints <ITestMessage1>() .Named("Obvs.TestService") .AppendMessageProperties(message => new Dictionary <string, string> { { "TestProperty", "123" } }) .FilterReceivedMessages(properties => true) .ConnectToKafka(_seed2Addresses) .SerializedAsJson() .AsClientAndServer() .PublishLocally() .OnlyMessagesWithNoEndpoints() .UsingConsoleLogging() .Create(); ConcurrentBag <IMessage> messages = new ConcurrentBag <IMessage>(); // create some actions that will act as a fake services acting on incoming commands and requests Action <TestCommand> fakeService1 = command => serviceBus.PublishAsync(new TestEvent { Id = command.Id }); Action <TestRequest> fakeService2 = request => serviceBus.ReplyAsync(request, new TestResponse { Id = request.Id }); AnonymousObserver <IMessage> observer = new AnonymousObserver <IMessage>(x => { Console.WriteLine("********* " + x); messages.Add(x); }, Console.WriteLine, () => Console.WriteLine("OnCompleted")); // subscribe to all messages on the ServiceBus CompositeDisposable subscriptions = new CompositeDisposable { serviceBus.Events.Subscribe(observer), serviceBus.Commands.Subscribe(observer), serviceBus.Requests.Subscribe(observer), serviceBus.Commands.OfType <TestCommand>().Subscribe(fakeService1), serviceBus.Requests.OfType <TestRequest>().Subscribe(fakeService2) }; // send some messages serviceBus.SendAsync(new TestCommand { Id = 123 }); serviceBus.SendAsync(new TestCommand2 { Id = 123 }); serviceBus.SendAsync(new TestCommand3 { Id = 123 }); serviceBus.GetResponses(new TestRequest { Id = 456 }).Subscribe(observer); // wait some time until we think all messages have been sent and received over AMQ Thread.Sleep(TimeSpan.FromSeconds(10)); // test we got everything we expected Assert.That(messages.OfType <TestCommand>().Count() == 1, "TestCommand not received"); Assert.That(messages.OfType <TestCommand2>().Count() == 1, "TestCommand2 not received"); Assert.That(messages.OfType <TestCommand3>().Count() == 1, "TestCommand3 not received"); Assert.That(messages.OfType <TestEvent>().Count() == 1, "TestEvent not received"); Assert.That(messages.OfType <TestRequest>().Count() == 1, "TestRequest not received"); Assert.That(messages.OfType <TestResponse>().Count() == 1, "TestResponse not received"); subscriptions.Dispose(); ((IDisposable)serviceBus).Dispose(); // win! }
protected void AddThread(Thread thread) { _threads.Add(thread); }
public void AddItem(NavigateToItem item) { _itemsReceived.Add(item); }
public Question AddQuestion([FromBody] Question question) { question.Id = Guid.NewGuid(); question.Answers = new List <Answer>(); questions.Add(question); return(question); }
private void LogRepository(IPackageRepository repository, Exception ex) { _failingRepositories.Add(repository); Logger.Log(MessageLevel.Warning, ExceptionUtility.Unwrap(ex).Message); }
private XE EntryAttribute(string catalog, IDataReader reader, StringDictionary dict , string gId , string sanitizedTitle , string linkCatalog , string linkSku , string gPrice , string gAdjustedPrice , string gAvailability , string gBrandName, string publisherName, XE contributors, string breadcrumb, bool isZeroCommissionProduct, string merchandiseType, IRuleEvaluationResult promotionalTextEvaluationResult, string description) { //entry var entry = new XE("product"); sanitizedTitle = GetCjString(sanitizedTitle, MaxTitleLength); var name = new XE("name", sanitizedTitle); entry.Add(name); var keywordsValue = string.Empty; // First get the major contributor text if (!string.IsNullOrWhiteSpace(gBrandName)) { keywordsValue = gBrandName; } else if (contributors != null) { keywordsValue = contributors.Value; } // Now add the breadcrumb if (!string.IsNullOrWhiteSpace(keywordsValue)) { keywordsValue += ", "; } keywordsValue += string.Join(", ", breadcrumb.Split(new[] { BreadcrumbTrailSplitter }, StringSplitOptions.RemoveEmptyEntries)) + ", "; keywordsValue += sanitizedTitle; var keywords = new XE("keywords", GetCjString(keywordsValue, MaxKeywordLength)); entry.Add(keywords); var descriptionValue = GetCjString(FeedUtils.RemoveHtmlTags(description), MaxDescriptionLength); if (string.IsNullOrWhiteSpace(descriptionValue)) { descriptionValue = sanitizedTitle; } var descriptionXe = new XE("description", descriptionValue); entry.Add(descriptionXe); var gaId = new XE("sku", gId); entry.Add(gaId); var aLink = FeedEntryLink(GetFeedEntryLinkValue(reader, linkCatalog, linkSku)); entry.Add(aLink); var available = new XE("available", "Yes"); entry.Add(available); var aImgLink = EntryImageLink(reader, linkSku); entry.Add(aImgLink); Decimal price; bool isSpecial = false; if (DisplaySalePriceInfo) { if (Decimal.TryParse(gPrice, out price)) { var gaPrice = new XE("price", price.ToString("F", CultureInfo.InvariantCulture)); entry.Add(gaPrice); Decimal salePrice; if (!string.IsNullOrWhiteSpace(gAdjustedPrice) && Decimal.TryParse(gAdjustedPrice, out salePrice) && salePrice != price) { isSpecial = true; var gaSalePrice = new XE("saleprice", salePrice.ToString("F", CultureInfo.InvariantCulture)); entry.Add(gaSalePrice); } } } else { price = Decimal.Parse(gAdjustedPrice); var gaPrice = new XE("price", price.ToString("F", CultureInfo.InvariantCulture)); entry.Add(gaPrice); } entry.Add(new XE("currency", "CAD")); // CJ expects the optional xml nodes in a certain order var isBook = catalog.Equals("books", StringComparison.OrdinalIgnoreCase); if (!isBook && (linkSku.Length == 12 || linkSku.Length == 13)) { entry.Add(new XE("upc", linkSku)); } if (promotionalTextEvaluationResult.HasMatch) { if (!promotionalTextEvaluationResult.IsDefaultMatch) { isSpecial = true; } var promoTextValue = GetCjString(promotionalTextEvaluationResult.MatchingRulePayLoads.First(), MaxPromotionalTextLength); entry.Add(new XE("promotionaltext", promoTextValue)); } var advertiserCategoryText = breadcrumb.Replace(BreadcrumbTrailSplitter, ">"); entry.Add(new XE("advertisercategory", GetCjString(advertiserCategoryText, MaxAdvertiserCategoryLength))); if (!string.IsNullOrWhiteSpace(gBrandName)) { var manufacturer = GetCjString(gBrandName, MaxManufacturerLength); entry.Add(new XE("manufacturer", manufacturer)); entry.Add(new XE("manufacturerid", linkSku)); } if (isBook) { entry.Add(new XE("isbn", linkSku)); if (contributors != null) { entry.Add(new XE("author", GetCjString(contributors.Value, MaxManufacturerLength))); } if (!string.IsNullOrWhiteSpace(publisherName)) { entry.Add(new XE("publisher", GetCjString(publisherName, MaxManufacturerLength))); } } else { if (contributors != null) { entry.Add(new XE("artist", GetCjString(contributors.Value, MaxManufacturerLength))); } } entry.Add(new XE("title", sanitizedTitle)); if (!isBook) { if (!string.IsNullOrWhiteSpace(publisherName)) { entry.Add(new XE("label", GetCjString(publisherName, MaxManufacturerLength))); } if (dict.ContainsKey("format")) { var format = reader[dict["format"]].ToString(); if (!string.IsNullOrWhiteSpace(format)) { entry.Add(new XE("format", format)); } } } entry.Add(new XE("special", (isSpecial) ? "Yes" : "No")); if (catalog.Equals("generalmerchandise", StringComparison.OrdinalIgnoreCase)) { entry.Add(new XE("gift", "Yes")); } entry.Add(new XE("instock", (string.IsNullOrWhiteSpace(gAvailability)) ? "No" : "Yes")); entry.Add(new XE("condition", "New")); if (!string.IsNullOrWhiteSpace(DefaultShippingCost)) { entry.Add(new XE("standardshippingcost", DefaultShippingCost)); } if (string.IsNullOrWhiteSpace(merchandiseType)) { entry.Add(new XE("merchandisetype", ZeroCommissionListName)); } else { if (isZeroCommissionProduct) { entry.Add(new XE("merchandisetype", ZeroCommissionListName)); // If the merchandise type has a different value and it's not equal to zero commission list // and if we're putting the item on the zero commission list, add it to the list of items to be // updated inside the if (!merchandiseType.Equals(ZeroCommissionListName, StringComparison.OrdinalIgnoreCase)) { _updatedMerchandiseTypeProductPids.Add(decimal.Parse(gId)); } Log.DebugFormat("Product {0} was put in zero commission list.", gId); } else { entry.Add(new XE("merchandisetype", merchandiseType)); } } return(entry); }
public void UpdateConnectionsDetails(ObservableCollection <ServerConnectionRow> NewConnectionList) { //check whick connections we should remove from existing list foreach (ServerConnectionStatus sc in ServerConnections) { if (sc.PendingRemove == true) { continue; } ServerConnectionRow scrExisting = null; foreach (ServerConnectionRow scr in NewConnectionList) { if (scr.IP == sc.IP && scr.Port == sc.Port) { scrExisting = scr; break; } } //should remove from our connection list if (scrExisting == null) { sc.PendingRemove = true; } //if connection is disabled, we will try to break an existing connection on next update if (scrExisting != null) { if (scrExisting.Delete_ != 0) { sc.PendingRemove = true; } sc.Enabled = scrExisting.Enabled; if (scrExisting.Name != null) { sc.ServerName = scrExisting.Name; } else { sc.ServerName = " "; } } } //check for connections we should add bool RefreshPersports = false; foreach (ServerConnectionRow scr in NewConnectionList) { //no need to save invalid rows if (scr.IP == null || scr.IP == "" || scr.Port <= 0) { continue; } ServerConnectionStatus Existingsc = null; foreach (ServerConnectionStatus sc in ServerConnections) { if (scr.IP == sc.IP && scr.Port == sc.Port && sc.PendingRemove == false) { Existingsc = sc; break; } } if (Existingsc != null) { continue; } //create a new connection ServerConnections.Add(new ServerConnectionStatus(scr.IP, scr.Port, -1, scr.Enabled, scr.Name)); //make sure we will refresh the persport for this server as soon as possible RefreshPersports = true; } if (RefreshPersports == true && Globals.persPortManager != null) { Globals.persPortManager.ForceStatusUpdate(); } }