System.Threading.Tasks.Parallel.ForEach(System.Collections.Concurrent.OrderablePartitioner, System.Threading.Tasks.ParallelOptions, System.Func, System.Func, System.Action)

Here are the examples of the csharp api System.Threading.Tasks.Parallel.ForEach(System.Collections.Concurrent.OrderablePartitioner, System.Threading.Tasks.ParallelOptions, System.Func, System.Func, System.Action) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1246 Examples 7

19 View Source File : BiotaGuidConsolidator.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static void ConsolidateBiotaGuids(uint startingGuid, out int numberOfBiotasConsolidated, out int numberOfErrors)
        {
            log.Info($"Consolidating biotas, starting at guid 0x{startingGuid:X8}...");

            Thread.Sleep(1000); // Give the logger type to flush to the client so that our output lines up in order

            Console.WriteLine("!!! Do not proceed unless you have backed up your shard database first !!!");
            Console.WriteLine("In the event of any failure, you may be asked to rollback your shard database.");
            Console.WriteLine("Press any key to proceed, or abort the process to quit.");
            Console.ReadLine();
            Console.WriteLine(".... hold on to your butts...");

            if (startingGuid < ObjectGuid.DynamicMin)
                throw new Exception($"startingGuid cannot be lower than ObjectGuid.DynamicMin (0x{ObjectGuid.DynamicMin:X8})");

            int numOfBiotasConsolidated = 0;
            int numOfErrors = 0;

            var shardDatabase = new ShardDatabase();

            var sequenceGaps = shardDatabase.GetSequenceGaps(ObjectGuid.DynamicMin, 10000000);
            var availableIDs = new LinkedList<(uint start, uint end)>(sequenceGaps);
            List<Biota> partialBiotas;

            using (var context = new ShardDbContext())
                partialBiotas = context.Biota.Where(r => r.Id >= startingGuid).OrderByDescending(r => r.Id).ToList();

            var idConversions = new ConcurrentDictionary<uint, uint>();

            // Process ConsolidatableBasicWeenieTypes first
            Parallel.ForEach(partialBiotas, partialBiota =>
            {
                if (numOfErrors > 0)
                    return;

                if (!ConsolidatableBasicWeenieTypes.Contains((WeenieType)partialBiota.WeenieType))
                    return;

                // Get the original biota
                var fullBiota = shardDatabase.GetBiota(partialBiota.Id, true);

                if (fullBiota == null)
                {
                    Interlocked.Increment(ref numOfErrors);
                    log.Warn($"Failed to get biota with id 0x{partialBiota.Id:X8} from the database. This shouldn't happen. It also shouldn't require a rollback.");
                    return;
                }

                // Get the next available id
                uint newId = 0;

                lock (availableIDs)
                {
                    if (availableIDs.First != null)
                    {
                        var id = availableIDs.First.Value.start;

                        if (availableIDs.First.Value.start == availableIDs.First.Value.end)
                            availableIDs.RemoveFirst();
                        else
                            availableIDs.First.Value = (availableIDs.First.Value.start + 1, availableIDs.First.Value.end);

                        newId = id;
                    }
                }

                if (newId == 0)
                {
                    Interlocked.Increment(ref numOfErrors);
                    log.Fatal("Failed to generate new id. No more id's available for consolidation. This shouldn't require a rollback.");
                    return;
                }

                idConversions[fullBiota.Id] = newId;

                // Copy our original biota into a new biota and set the new id
                var converted = BiotaConverter.ConvertToEnreplacedyBiota(fullBiota);
                converted.Id = newId;

                // Save the new biota
                if (!shardDatabase.SaveBiota(converted, new ReaderWriterLockSlim()))
                {
                    Interlocked.Increment(ref numOfErrors);
                    log.Fatal($"Failed to save new biota with id 0x{fullBiota.Id:X8} to the database. Please rollback your shard.");
                    return;
                }

                // Finally, remove the original biota
                if (!shardDatabase.RemoveBiota(fullBiota.Id))
                {
                    Interlocked.Increment(ref numOfErrors);
                    log.Fatal($"Failed to remove original biota with id 0x{fullBiota.Id:X8} from database. Please rollback your shard.");
                    return;
                }

                var tempNumOfBiotasConsolidated = Interlocked.Increment(ref numOfBiotasConsolidated);

                if ((tempNumOfBiotasConsolidated + numOfErrors) % 1000 == 0)
                    Console.WriteLine($"{tempNumOfBiotasConsolidated:N0} biotas successfully processed out of {partialBiotas.Count:N0}...");
            });


            // Process ConsolidatableContainerWeenieTypes second
            foreach (var partialBiota in partialBiotas)
            {
                if (numOfErrors > 0)
                    break;

                if (!ConsolidatableContainerWeenieTypes.Contains((WeenieType)partialBiota.WeenieType))
                    continue;

                // Get the original biota
                var fullBiota = shardDatabase.GetBiota(partialBiota.Id, true);

                if (fullBiota == null)
                {
                    Interlocked.Increment(ref numOfErrors);
                    log.Warn($"Failed to get biota with id 0x{partialBiota.Id:X8} from the database. This shouldn't happen. It also shouldn't require a rollback.");
                    break;
                }

                // Get the next available id
                uint newId = 0;

                lock (availableIDs)
                {
                    if (availableIDs.First != null)
                    {
                        var id = availableIDs.First.Value.start;

                        if (availableIDs.First.Value.start == availableIDs.First.Value.end)
                            availableIDs.RemoveFirst();
                        else
                            availableIDs.First.Value = (availableIDs.First.Value.start + 1, availableIDs.First.Value.end);

                        newId = id;
                    }
                }

                if (newId == 0)
                {
                    Interlocked.Increment(ref numOfErrors);
                    log.Fatal("Failed to generate new id. No more id's available for consolidation. This shouldn't require a rollback.");
                    break;
                }

                idConversions[fullBiota.Id] = newId;

                // Copy our original biota into a new biota and set the new id
                var converted = BiotaConverter.ConvertToEnreplacedyBiota(fullBiota);
                converted.Id = newId;

                // Save the new biota
                if (!shardDatabase.SaveBiota(converted, new ReaderWriterLockSlim()))
                {
                    Interlocked.Increment(ref numOfErrors);
                    log.Fatal($"Failed to save new biota with id 0x{fullBiota.Id:X8} to the database. Please rollback your shard.");
                    break;
                }

                // update contained items to point to the new container
                using (var context = new ShardDbContext())
                {
                    var ownedItems = context.BiotaPropertiesIID.Where(r => r.Type == (ushort)PropertyInstanceId.Owner && r.Value == fullBiota.Id);

                    foreach (var item in ownedItems)
                        item.Value = converted.Id;

                    var containedItems = context.BiotaPropertiesIID.Where(r => r.Type == (ushort)PropertyInstanceId.Container && r.Value == fullBiota.Id);

                    foreach (var item in containedItems)
                        item.Value = converted.Id;

                    context.SaveChanges();
                }

                // Finally, remove the original biota
                if (!shardDatabase.RemoveBiota(fullBiota.Id))
                {
                    Interlocked.Increment(ref numOfErrors);
                    log.Fatal($"Failed to remove original biota with id 0x{fullBiota.Id:X8} from database. Please rollback your shard.");
                    break;
                }

                var tempNumOfBiotasConsolidated = Interlocked.Increment(ref numOfBiotasConsolidated);

                if ((tempNumOfBiotasConsolidated + numOfErrors) % 1000 == 0)
                    Console.WriteLine($"{tempNumOfBiotasConsolidated:N0} biotas successfully processed out of {partialBiotas.Count:N0}...");
            }


            // Update enchantment tables for equipped items
            using (var context = new ShardDbContext())
            {
                var enchantments = context.BiotaPropertiesEnchantmentRegistry.Where(r => r.CasterObjectId >= startingGuid).ToList();

                // First, remove the enchantments from the database
                foreach (var enchantment in enchantments)
                {
                    if (idConversions.TryGetValue(enchantment.CasterObjectId, out var newId))
                        context.BiotaPropertiesEnchantmentRegistry.Remove(enchantment);
                }

                context.SaveChanges();

                // Second, re-id them and add them back
                foreach (var enchantment in enchantments)
                {
                    if (idConversions.TryGetValue(enchantment.CasterObjectId, out var newId))
                    {
                        enchantment.CasterObjectId = newId;

                        context.BiotaPropertiesEnchantmentRegistry.Add(enchantment);
                    }
                }

                var shortcuts = context.CharacterPropertiesShortcutBar.Where(r => r.ShortcutObjectId >= startingGuid).ToList();

                foreach (var shortcut in shortcuts)
                {
                    if (idConversions.TryGetValue(shortcut.ShortcutObjectId, out var newId))
                        shortcut.ShortcutObjectId = newId;
                }

                context.SaveChanges();
            }


            // Finished
            numberOfBiotasConsolidated = numOfBiotasConsolidated;
            numberOfErrors = numOfErrors;

            log.Info($"Consolidated {numberOfBiotasConsolidated:N0} biotas with {numberOfErrors:N0} errors out of {partialBiotas.Count:N0} total.");
        }

19 View Source File : ShardDatabase.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public bool SaveBiotasInParallel(IEnumerable<(ACE.Enreplacedy.Models.Biota biota, ReaderWriterLockSlim rwLock)> biotas)
        {
            var result = true;

            Parallel.ForEach(biotas, ConfigManager.Config.Server.Threading.DatabaseParallelOptions, biota =>
            {
                if (!SaveBiota(biota.biota, biota.rwLock))
                    result = false;
            });

            return result;
        }

19 View Source File : ShardDatabase.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public List<Biota> GetWieldedItemsInParallel(uint parentId)
        {
            var wieldedItems = new ConcurrentBag<Biota>();

            using (var context = new ShardDbContext())
            {
                context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

                var results = context.BiotaPropertiesIID
                    .Where(r => r.Type == (ushort)PropertyInstanceId.Wielder && r.Value == parentId)
                    .ToList();

                Parallel.ForEach(results, ConfigManager.Config.Server.Threading.DatabaseParallelOptions, result =>
                {
                    var biota = GetBiota(result.ObjectId);

                    if (biota != null)
                        wieldedItems.Add(biota);
                });
            }

            return wieldedItems.ToList();
        }

19 View Source File : ShardDatabase.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public bool RemoveBiotasInParallel(IEnumerable<uint> ids)
        {
            var result = true;

            Parallel.ForEach(ids, ConfigManager.Config.Server.Threading.DatabaseParallelOptions, id =>
            {
                if (!RemoveBiota(id))
                    result = false;
            });

            return result;
        }

19 View Source File : ShardDatabase.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public List<Biota> GetInventoryInParallel(uint parentId, bool includedNestedItems)
        {
            var inventory = new ConcurrentBag<Biota>();

            using (var context = new ShardDbContext())
            {
                context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

                var results = context.BiotaPropertiesIID
                    .Where(r => r.Type == (ushort)PropertyInstanceId.Container && r.Value == parentId)
                    .ToList();

                Parallel.ForEach(results, ConfigManager.Config.Server.Threading.DatabaseParallelOptions, result =>
                {
                    var biota = GetBiota(result.ObjectId);

                    if (biota != null)
                    {
                        inventory.Add(biota);

                        if (includedNestedItems && biota.WeenieType == (int)WeenieType.Container)
                        {
                            var subItems = GetInventoryInParallel(biota.Id, false);

                            foreach (var subItem in subItems)
                                inventory.Add(subItem);
                        }
                    }
                });
            }

            return inventory.ToList();
        }

19 View Source File : ShardDatabase.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public List<ACE.Enreplacedy.Models.Biota> GetAllPlayerBiotasInParallel()
        {
            var biotas = new ConcurrentBag<ACE.Enreplacedy.Models.Biota>();

            using (var context = new ShardDbContext())
            {
                var results = context.Character
                    .Where(r => !r.IsDeleted)
                    .AsNoTracking()
                    .ToList();

                Parallel.ForEach(results, result =>
                {
                    var biota = GetBiota(result.Id, true);

                    if (biota != null)
                    {
                        var convertedBiota = ACE.Database.Adapter.BiotaConverter.ConvertToEnreplacedyBiota(biota);

                        biotas.Add(convertedBiota);
                    }
                    else
                        log.Error($"ShardDatabase.GetAllPlayerBiotasInParallel() - couldn't find biota for character 0x{result.Id:X8}");
                });
            }

            return biotas.ToList();
        }

19 View Source File : LandblockManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static void TickPhysics(double portalYearTicks)
        {
            ProcessPendingLandblockGroupAdditions();

            var movedObjects = new ConcurrentBag<WorldObject>();

            if (ConfigManager.Config.Server.Threading.MulreplacedhreadedLandblockGroupPhysicsTicking)
            {
                CurrentlyTickingLandblockGroupsMulreplacedhreaded = true;

                Parallel.ForEach(landblockGroups, ConfigManager.Config.Server.Threading.LandblockManagerParallelOptions, landblockGroup =>
                {
                    CurrentMulreplacedhreadedTickingLandblockGroup.Value = landblockGroup;

                    foreach (var landblock in landblockGroup)
                        landblock.TickPhysics(portalYearTicks, movedObjects);

                    CurrentMulreplacedhreadedTickingLandblockGroup.Value = null;
                });

                CurrentlyTickingLandblockGroupsMulreplacedhreaded = false;
            }
            else
            {
                foreach (var landblockGroup in landblockGroups)
                {
                    foreach (var landblock in landblockGroup)
                        landblock.TickPhysics(portalYearTicks, movedObjects);
                }
            }

            // iterate through objects that have changed landblocks
            foreach (var movedObject in movedObjects)
            {
                // NOTE: The object's Location can now be null, if a player logs out, or an item is picked up
                if (movedObject.Location == null)
                    continue;

                // replacedume adjacency move here?
                RelocateObjectForPhysics(movedObject, true);
            }
        }

19 View Source File : PlayerManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static void Initialize()
        {
            var results = DatabaseManager.Shard.BaseDatabase.GetAllPlayerBiotasInParallel();

            Parallel.ForEach(results, ConfigManager.Config.Server.Threading.DatabaseParallelOptions, result =>
            {
                var offlinePlayer = new OfflinePlayer(result);

                lock (offlinePlayers)
                    offlinePlayers[offlinePlayer.Guid.Full] = offlinePlayer;
            });
        }

19 View Source File : LandblockManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static void TickMulreplacedhreadedWork()
        {
            ProcessPendingLandblockGroupAdditions();

            if (ConfigManager.Config.Server.Threading.MulreplacedhreadedLandblockGroupTicking)
            {
                CurrentlyTickingLandblockGroupsMulreplacedhreaded = true;

                Parallel.ForEach(landblockGroups, ConfigManager.Config.Server.Threading.LandblockManagerParallelOptions, landblockGroup =>
                {
                    CurrentMulreplacedhreadedTickingLandblockGroup.Value = landblockGroup;

                    foreach (var landblock in landblockGroup)
                        landblock.TickMulreplacedhreadedWork(Time.GetUnixTime());

                    CurrentMulreplacedhreadedTickingLandblockGroup.Value = null;
                });

                CurrentlyTickingLandblockGroupsMulreplacedhreaded = false;
            }
            else
            {
                foreach (var landblockGroup in landblockGroups)
                {
                    foreach (var landblock in landblockGroup)
                        landblock.TickMulreplacedhreadedWork(Time.GetUnixTime());
                }
            }
        }

19 View Source File : NetworkManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static int DoSessionWork()
        {
            int sessionCount = 0;

            sessionLock.EnterUpgradeableReadLock();
            try
            {
                // The session tick outbound processes pending actions and handles outgoing messages
                ServerPerformanceMonitor.RestartEvent(ServerPerformanceMonitor.MonitorType.DoSessionWork_TickOutbound);
                Parallel.ForEach(sessionMap, ConfigManager.Config.Server.Threading.NetworkManagerParallelOptions, s => s?.TickOutbound());
                ServerPerformanceMonitor.RegisterEventEnd(ServerPerformanceMonitor.MonitorType.DoSessionWork_TickOutbound);

                // Removes sessions in the NetworkTimeout state, including sessions that have reached a timeout limit.
                ServerPerformanceMonitor.RestartEvent(ServerPerformanceMonitor.MonitorType.DoSessionWork_RemoveSessions);
                foreach (var session in sessionMap.Where(k => !Equals(null, k)))
                {
                    if (session.PendingTermination != null && session.PendingTermination.TerminationStatus == SessionTerminationPhase.SessionWorkCompleted)
                    {
                        session.DropSession();
                        session.PendingTermination.TerminationStatus = SessionTerminationPhase.WorldManagerWorkCompleted;
                    }

                    sessionCount++;
                }
                ServerPerformanceMonitor.RegisterEventEnd(ServerPerformanceMonitor.MonitorType.DoSessionWork_RemoveSessions);
            }
            finally
            {
                sessionLock.ExitUpgradeableReadLock();
            }
            return sessionCount;
        }

19 View Source File : PXGraphAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

protected override void replacedyzeSymbol(SymbolreplacedysisContext context, PXContext pxContext)
		{
			context.CancellationToken.ThrowIfCancellationRequested();

			if (!(context.Symbol is INamedTypeSymbol type))
			{
				return;
			}

			ParallelOptions parallelOptions = new ParallelOptions
			{
				CancellationToken = context.CancellationToken
			};

			var inferredGraphs = PXGraphSemanticModel.InferModels(pxContext, type, GraphSemanticModelCreationOptions.CollectAll, context.CancellationToken);
			
			foreach (var graph in inferredGraphs)
			{
				Parallel.ForEach(_innerreplacedyzers, parallelOptions, innerreplacedyzer =>
				{
					context.CancellationToken.ThrowIfCancellationRequested();

					if (innerreplacedyzer.Shouldreplacedyze(pxContext, graph))
					{
						innerreplacedyzer.replacedyze(context, pxContext, graph);
					}
				});
			}
		}

19 View Source File : DacPropertyAttributesAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override void replacedyze(SymbolreplacedysisContext context, PXContext pxContext, DacSemanticModel dacOrDacExt)
		{
			FieldTypeAttributesRegister fieldAttributesRegister = new FieldTypeAttributesRegister(pxContext);

			if (dacOrDacExt.PropertiesByNames.Count >= DacPropertiesConcurrentreplacedysisThreshold)	//Do concurrent replacedysis only for big DACs
			{
				ParallelOptions parallelOptions = new ParallelOptions
				{
					CancellationToken = context.CancellationToken,
					MaxDegreeOfParallelism = MaxThreadsCount
				};

				Parallel.ForEach(dacOrDacExt.AllDeclaredProperties, parallelOptions,
								 property => CheckDacProperty(property, context, pxContext, fieldAttributesRegister));
			}
			else
			{
				foreach (DacPropertyInfo property in dacOrDacExt.AllDeclaredProperties)
				{
					CheckDacProperty(property, context, pxContext, fieldAttributesRegister);
				}
			}
		}

19 View Source File : DacAnalyzersAggregator.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

protected override void replacedyzeSymbol(SymbolreplacedysisContext context, PXContext pxContext)
		{
			context.CancellationToken.ThrowIfCancellationRequested();

			if (!(context.Symbol is INamedTypeSymbol type))
				return;

			var inferredDacModel = DacSemanticModel.InferModel(pxContext, type, context.CancellationToken);

			if (inferredDacModel == null)
				return;

			ParallelOptions parallelOptions = new ParallelOptions
			{
				CancellationToken = context.CancellationToken
			};

			Parallel.ForEach(_innerreplacedyzers, parallelOptions, innerreplacedyzer =>
			{
				context.CancellationToken.ThrowIfCancellationRequested();

				if (innerreplacedyzer.Shouldreplacedyze(pxContext, inferredDacModel))
				{
					innerreplacedyzer.replacedyze(context, pxContext, inferredDacModel);
				}
			});
		}

19 View Source File : EventHandlerAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

protected override void replacedyzeSymbol(SymbolreplacedysisContext context, PXContext pxContext)
		{
			context.CancellationToken.ThrowIfCancellationRequested();

			if (!(context.Symbol is IMethodSymbol methodSymbol))
				return;
		
			EventType eventType = methodSymbol.GetEventHandlerType(pxContext);

			if (eventType == EventType.None)
				return;

			ParallelOptions parallelOptions = new ParallelOptions
			{
				CancellationToken = context.CancellationToken
			};

			Parallel.ForEach(_innerreplacedyzers, parallelOptions, innerreplacedyzer =>
			{
				context.CancellationToken.ThrowIfCancellationRequested();

				if (innerreplacedyzer.Shouldreplacedyze(pxContext, eventType))
				{
					innerreplacedyzer.replacedyze(context, pxContext, eventType);
				}
			});
		}

19 View Source File : PXRegexColorizerTagger.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private void GetTagsFromSnapshot(ITextSnapshot newSnapshot)
		{
			string wholeText = newSnapshot.GetText();
            var matches = RegExpressions.BQLSelectCommandRegex
                                        .Matches(wholeText)
							            .OfType<Match>()
							            .Where(bqlCommandMatch => !string.IsNullOrWhiteSpace(bqlCommandMatch.Value));

            Parallel.ForEach(matches, 
                             bqlCommandMatch => GetTagsFromBQLCommand(newSnapshot, bqlCommandMatch.Value, bqlCommandMatch.Index));
        }

19 View Source File : ContentMapProvider.cs
License : MIT License
Project Creator : Adoxio

protected virtual IEnumerable<Enreplacedy> GetEnreplacedies(CrmDbContext context, SolutionDefinition solution, IDictionary<string, object> parameters)
		{
			ConcurrentBag<Enreplacedy> result = new ConcurrentBag<Enreplacedy>();
			var queries = solution.GetQueries(parameters).Where(query => query != null);

			Parallel.ForEach(queries, query =>
			{
				// Add content map enreplacedies explicitly to the Portalused enreplacedies list. 
				// Since we are skipping cache for content map enreplacedies and hence these enreplacedies won't be added in this list via Dependency calucaltion.
				ADXTrace.Instance.TraceVerbose(TraceCategory.Application, $"Enreplacedy {query.Enreplacedy.Name} is added to Enabled Enreplacedy List for Portal Cache ");
				WebAppConfigurationProvider.PortalUsedEnreplacedies.TryAdd(query.Enreplacedy.Name, true);
				Fetch(context.Service, query, result);
			});

			return result.AsEnumerable();
		}

19 View Source File : IZeroObject.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

internal static void OnZeroInitialize()
        {
            using (OnceScope.CreateScope(ZeroObjects))
            {
                ZeroTrace.SystemLog("[OnZeroInitialize>>");
                Parallel.ForEach(ZeroObjects.Values.ToArray(), obj =>
                {
                    try
                    {
                        obj.OnZeroInitialize();
                        ZeroTrace.SystemLog(obj.Name, "Initialize");
                    }
                    catch (Exception e)
                    {
                        ZeroTrace.WriteException(obj.Name, e, "*Initialize");
                    }
                });
                ZeroTrace.SystemLog("<<OnZeroInitialize]");
            }
        }

19 View Source File : IZeroObject.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

internal static void OnStationStateChanged(StationConfig config)
        {
            using (OnceScope.CreateScope(ZeroObjects))
            {
                ZeroTrace.SystemLog($"[OnStationStateChanged({config.StationName})>>");
                Parallel.ForEach(ActiveObjects.Where(p => string.Equals(config.StationName, p.StationName, StringComparison.OrdinalIgnoreCase)).ToArray(),
                    obj =>
                {
                    try
                    {
                        obj.OnStationStateChanged(config);
                    }
                    catch (Exception e)
                    {
                        ZeroTrace.WriteException(obj.Name, e, "OnStationStateChanged");
                    }
                });
                ZeroTrace.SystemLog($"<<OnStationStateChanged({config.StationName})]");
            }
        }

19 View Source File : IZeroObject.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

internal static void OnZeroEnd()
        {
            RaiseEvent(ZeroNetEventType.AppStop);
            using (OnceScope.CreateScope(ZeroObjects))
            {
                ZeroTrace.SystemLog("[OnZeroEnd>>");
                SystemManager.Instance.HeartLeft();
                ApplicationState = StationState.Closing;
                if (HaseActiveObject)
                {
                    Parallel.ForEach(ActiveObjects.ToArray(), obj =>
                    {
                        try
                        {
                            ZeroTrace.SystemLog(obj.Name, "*Close");
                            obj.OnZeroEnd();
                        }
                        catch (Exception e)
                        {
                            ZeroTrace.WriteException(obj.Name, e, "*Close");
                        }
                    });
                    WaitAllObjectSemapreplaced();
                }
                GC.Collect();
                ApplicationState = StationState.Closed;
                ZeroTrace.SystemLog("<<OnZeroEnd]");
            }
        }

19 View Source File : IZeroObject.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

internal static void OnZeroDestory()
        {
            if (!Monitor.TryEnter(ZeroObjects))
                return;
            ZeroTrace.SystemLog("[OnZeroDestory>>");
            RaiseEvent(ZeroNetEventType.AppEnd);
            using (OnceScope.CreateScope(ZeroObjects))
            {
                var array = ZeroObjects.Values.ToArray();
                ZeroObjects.Clear();
                Parallel.ForEach(array, obj =>
                {
                    try
                    {
                        ZeroTrace.SystemLog(obj.Name, "*Destory");
                        obj.OnZeroDestory();
                    }
                    catch (Exception e)
                    {
                        ZeroTrace.WriteException(obj.Name, e, "*Destory");
                    }
                });

                GC.Collect();
                ZeroTrace.SystemLog("<<OnZeroDestory]");

                ZeroTrace.SystemLog("[OnZeroDispose>>");
                Parallel.ForEach(array, obj =>
                {
                    try
                    {
                        ZeroTrace.SystemLog(obj.Name, "*Dispose");
                        obj.Dispose();
                    }
                    catch (Exception e)
                    {
                        ZeroTrace.WriteException(obj.Name, e, "*Dispose");
                    }
                });
                ZeroTrace.SystemLog("<<OnZeroDispose]");
            }
        }

19 View Source File : CustomBatchFixAllProvider.cs
License : Apache License 2.0
Project Creator : agoda-com

public virtual async Task<CodeAction> GetFixAsync(
            ImmutableDictionary<Doreplacedent, ImmutableArray<Diagnostic>> doreplacedentsAndDiagnosticsToFixMap,
            FixAllContext fixAllContext)
        {
            if (doreplacedentsAndDiagnosticsToFixMap != null && doreplacedentsAndDiagnosticsToFixMap.Any())
            {
                fixAllContext.CancellationToken.ThrowIfCancellationRequested();

                var doreplacedents = doreplacedentsAndDiagnosticsToFixMap.Keys.ToImmutableArray();
                var fixesBag = new List<CodeAction>[doreplacedents.Length];
                var options = new ParallelOptions {CancellationToken = fixAllContext.CancellationToken};
                Parallel.ForEach(doreplacedents, options, (doreplacedent, state, index) =>
                {
                    fixAllContext.CancellationToken.ThrowIfCancellationRequested();
                    fixesBag[index] = new List<CodeAction>();
                    AddDoreplacedentFixesAsync(doreplacedent, doreplacedentsAndDiagnosticsToFixMap[doreplacedent], fixesBag[index].Add, fixAllContext).Wait(fixAllContext.CancellationToken);
                });

                if (fixesBag.Any(fixes => fixes.Count > 0))
                {
                    return await TryGetMergedFixAsync(fixesBag.SelectMany(i => i), fixAllContext).ConfigureAwait(false);
                }
            }

            return null;
        }

19 View Source File : CustomBatchFixAllProvider.cs
License : Apache License 2.0
Project Creator : agoda-com

public virtual async Task<CodeAction> GetFixAsync(
            ImmutableDictionary<Project, ImmutableArray<Diagnostic>> projectsAndDiagnosticsToFixMap,
            FixAllContext fixAllContext)
        {
            if (projectsAndDiagnosticsToFixMap != null && projectsAndDiagnosticsToFixMap.Any())
            {
                var options = new ParallelOptions {CancellationToken = fixAllContext.CancellationToken};
                var fixesBag = new List<CodeAction>[projectsAndDiagnosticsToFixMap.Count];
                Parallel.ForEach(projectsAndDiagnosticsToFixMap.Keys, options, (project, state, index) =>
                {
                    fixAllContext.CancellationToken.ThrowIfCancellationRequested();
                    var diagnostics = projectsAndDiagnosticsToFixMap[project];
                    fixesBag[index] = new List<CodeAction>();
                    AddProjectFixesAsync(project, diagnostics, fixesBag[index].Add, fixAllContext).Wait(fixAllContext.CancellationToken);
                });

                if (fixesBag.Any(fixes => fixes.Count > 0))
                {
                    return await TryGetMergedFixAsync(fixesBag.SelectMany(i => i), fixAllContext).ConfigureAwait(false);
                }
            }

            return null;
        }

19 View Source File : FixAllContextHelper.cs
License : Apache License 2.0
Project Creator : agoda-com

public static async Task<ImmutableDictionary<Project, ImmutableArray<Diagnostic>>> GetProjectDiagnosticsToFixAsync(FixAllContext fixAllContext)
        {
            var project = fixAllContext.Project;
            if (project != null)
            {
                switch (fixAllContext.Scope)
                {
                    case FixAllScope.Project:
                        var diagnostics = await fixAllContext.GetProjectDiagnosticsAsync(project).ConfigureAwait(false);
                        return ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Empty.Sereplacedem(project, diagnostics);

                    case FixAllScope.Solution:
                        var projectsAndDiagnostics = new ConcurrentDictionary<Project, ImmutableArray<Diagnostic>>();
                        var options = new ParallelOptions {CancellationToken = fixAllContext.CancellationToken};
                        Parallel.ForEach(project.Solution.Projects, options, proj =>
                        {
                            fixAllContext.CancellationToken.ThrowIfCancellationRequested();
                            var projectDiagnosticsTask = fixAllContext.GetProjectDiagnosticsAsync(proj);
                            projectDiagnosticsTask.Wait(fixAllContext.CancellationToken);
                            var projectDiagnostics = projectDiagnosticsTask.Result;
                            if (projectDiagnostics.Any())
                            {
                                projectsAndDiagnostics.TryAdd(proj, projectDiagnostics);
                            }
                        });

                        return projectsAndDiagnostics.ToImmutableDictionary();
                }
            }

            return ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Empty;
        }

19 View Source File : MessageEffectsControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private void GenerateResults(CancellationToken cancellationToken)
        {
            var uiDispatcher = Ioc.Default.GetService<IUserInterfaceDispatchService>();
            uiDispatcher.Invoke(() =>
            {
                this.GeneratedMessages.Clear();
            });

            var parallelOptions = new ParallelOptions()
            {
                CancellationToken = cancellationToken,
            };

            // Run all generators in parallel in case one plugin hangs or runs very slowly
            var pluginManager = Ioc.Default.GetService<IPluginManagerService>();
            Parallel.ForEach(pluginManager.MessageComposePlugins, parallelOptions, async (plugin) =>
            {
                if (parallelOptions.CancellationToken.IsCancellationRequested)
                {
                    return;
                }

                try
                {
                    var results = await plugin.ProvideOptions(this.TypedMessageContents);
                    foreach (var text in results.TextOptions)
                    {
                        if (parallelOptions.CancellationToken.IsCancellationRequested)
                        {
                            return;
                        }

                        var textResults = new SuggestedMessage { Message = text, Plugin = plugin.EffectPluginName };

                        uiDispatcher.Invoke(() =>
                        {
                            this.GeneratedMessages.Add(textResults);
                        });
                    }
                }
                catch (Exception)
                {
                }
            });
        }

19 View Source File : MessageEffectsControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private void GenerateResults(CancellationToken cancellationToken)
        {
            var generatedResults = new List<SuggestedMessage>();

            var parallelOptions = new ParallelOptions()
            {
                CancellationToken = cancellationToken,
            };

            // Run all generators in parallel in case one plugin hangs or runs very slowly
            try
            {
                Parallel.ForEach(Plugins.PluginManager.Instance.MessageComposePlugins, parallelOptions, async (plugin) =>
                {
                    if (parallelOptions.CancellationToken.IsCancellationRequested)
                    {
                        return;
                    }

                    try
                    {
                        var results = await plugin.ProvideOptions(this.TypedMessageContents);
                        foreach (var text in results.TextOptions)
                        {
                            if (parallelOptions.CancellationToken.IsCancellationRequested)
                            {
                                return;
                            }

                            var textResults = new SuggestedMessage { Message = text, Plugin = plugin.EffectPluginName };
                            generatedResults.Add(textResults);
                        }
                    }
                    catch (Exception)
                    {
                    }
                });
            }
            catch (Exception)
            {
            }

            this.GeneratedMessages = new DataGridCollectionView(generatedResults);
            this.GeneratedMessages.GroupDescriptions.Add(new DataGridPathGroupDescription(nameof(SuggestedMessage.Plugin)));
        }

19 View Source File : HyperbolicCoordinatesPostProcessorSystem.cs
License : MIT License
Project Creator : allenwp

public static void PostProcess(List<Sample3D[]> samples3D, PostProcessor3D postProcessor)
        {
            HyperbolicCoordinatesPostProcessor hyperbolicPP = postProcessor as HyperbolicCoordinatesPostProcessor;

            var origin = hyperbolicPP.Origin.Position;
            var zScale = hyperbolicPP.ZScale;

            var rangeParreplacedioner = Parreplacedioner.Create(samples3D);
            Parallel.ForEach(rangeParreplacedioner, samples3DArray =>
            {
                for (int i = 0; i < samples3DArray.Length; i++)
                {
                    var newPosition = samples3DArray[i].Position - origin;
                    newPosition.Z *= zScale;

                    // https://stackoverflow.com/questions/23744120/conversion-from-rectangular-to-hyperbolic-coordinates-not-reversible
                    newPosition = new Vector3(newPosition.X, (float)Math.Sqrt(newPosition.Z * newPosition.Y), (float)Math.Log(newPosition.Y / newPosition.Z));

                    newPosition += origin;
                    samples3DArray[i].Position = newPosition;
                }
            });
        }

19 View Source File : PolarCoordinatesPostProcessorSystem.cs
License : MIT License
Project Creator : allenwp

public static void PostProcess(List<Sample3D[]> samples3D, PostProcessor3D postProcessor)
        {
            PolarCoordinatesPostProcessor polarPP = postProcessor as PolarCoordinatesPostProcessor;

            var origin = polarPP.Origin.Position;
            var zScale = polarPP.ZScale;

            var rangeParreplacedioner = Parreplacedioner.Create(samples3D);
            Parallel.ForEach(rangeParreplacedioner, samples3DArray =>
            {
                for (int i = 0; i < samples3DArray.Length; i++)
                {
                    var newPosition = samples3DArray[i].Position - origin;
                    var scaledZ = newPosition.Z* zScale; // TODO: z-scale based on distance of "ground" from origin??? This might be possilbe to make this automatic based on that...
                    if (scaledZ > Math.PI / 2f || scaledZ < -1 * Math.PI / 2f)
                    {
                        samples3DArray[i].Disabled = true;
                    }
                    else
                    {
                        newPosition = Vector3.Transform(new Vector3(newPosition.X, newPosition.Y, 0f), Quaternion.CreateFromYawPitchRoll(0, scaledZ, 0));

                        newPosition += origin;
                        samples3DArray[i].Position = newPosition;
                    }
                }
            });
        }

19 View Source File : RadialPulsePostProcessorSystem.cs
License : MIT License
Project Creator : allenwp

public static void PostProcess(List<Sample3D[]> samples3D, PostProcessor3D postProcessor)
        {
            RadialPulsePostProcessor pulse = postProcessor as RadialPulsePostProcessor;

            var pos = pulse.Position;
            var min = pulse.CurrentMinDistance;
            var max = pulse.CurrentMaxDistance;
            var rangeParreplacedioner = Parreplacedioner.Create(samples3D);
            Parallel.ForEach(rangeParreplacedioner, samples3DArray =>
            {
                for (int i = 0; i < samples3DArray.Length; i++)
                {
                    float distance = Vector3.Distance(samples3DArray[i].Position, pos);
                    if (distance > max || distance < min)
                    {
                        samples3DArray[i].Disabled = true;
                    }
                }
            });
        }

19 View Source File : VectorTests.cs
License : MIT License
Project Creator : allisterb

private byte[] _MandelbrotManagedv4()
        {
            byte[] output = new byte[Mandelbrot_Height * Mandelbrot_Width];
            Vector<int> One = Vector<int>.One;
            Vector<int> Zero = Vector<int>.Zero;
            float[] Vectors = new float[6];
            Span<Vector2> Vector2Span = new Span<float>(Vectors).NonPortableCast<float, Vector2>(); //Lets us read individual Vector2

            Vectors[0] = -2f;
            Vectors[1] = -1f;
            Vectors[2] = 1f;
            Vectors[3] = 1f;
            Vectors[4] = Mandelbrot_Width;
            Vectors[5] = Mandelbrot_Height;

            Vector2 C0 = Vector2Span[0];
            Vector2 C1 = Vector2Span[1];
            Vector2 B = Vector2Span[2];
            Vector2 D = (C1 - C0) / B;

            
            for (int j = 0; j < Mandelbrot_Height; j++)
            {
                Parallel.ForEach(MandelbrotBitmapLocation(j), (p) =>
                {
                    int i = p.Item1;
                    float[] Pre = new float[VectorWidth];
                    float[] Pim = new float[VectorWidth];
                    for (int h = 0; h < VectorWidth; h++)
                    {
                        Pre[h] = C0.X + (D.X * (i + h));
                        Pim[h] = C0.Y + (D.Y * p.Item2);
                    }
                    int index = unchecked(p.Item2 * Mandelbrot_Width + i);
                    Vector<float> Vre = new Vector<float>(Pre);
                    Vector<float> Vim = new Vector<float>(Pim);
                    Vector<int> outputVector = GetByte(ref Vre, ref Vim, 255);
                    for (int h = 0; h < VectorWidth; h++)
                    {
                        output[index + h] = outputVector[h] < 255 ? (byte)outputVector[h] : (byte)255;
                    }
                });

            }
            return output;

            Vector<int> GetByte(ref Vector<float> Cre, ref Vector<float> Cim, int max_iterations)
            {
                Vector<float> Limit = new Vector<float>(4);
                Vector<int> MaxIterations = new Vector<int>(max_iterations);
                Vector<float> Zre = Cre; //make a copy
                Vector<float> Zim = Cim; //make a copy

                Vector<int> Increment = One;
                Vector<int> I;
                for (I = Zero; Increment != Zero; I += Vector.Abs(Increment))
                {
                    Vector<float> S = SquareAbs(Zre, Zim);
                    Increment = Vector.LessThanOrEqual(S, Limit) & Vector.LessThan(I, MaxIterations);
                    if (Increment == Zero)
                    {
                        break;
                    }
                    else
                    {
                        Vector<float> Tre = Zre;
                        Vector<float> Tim = Zim;
                        Zre = Cre + (Tre * Tre - Tim * Tim);
                        Zim = Cim + 2f * Tre * Tim;
                    }
                }
                return I;
            }

            Vector<float> SquareAbs(Vector<float> Vre, Vector<float> Vim)
            {
                return (Vre * Vre) + (Vim * Vim);
            }

            IEnumerable<ValueTuple<int, int>> MandelbrotBitmapLocation(int j)
            {
                for (int i = 0; i < Mandelbrot_Width; i += VectorWidth)
                {
                    yield return (i, j);
                }
            }
        }

19 View Source File : GuidObjectFolder.cs
License : MIT License
Project Creator : Alprog

private void SaveToFolder(string folderPath, HashSet<string> oldFiles)
            {
                Utils.EnsureDirectory(folderPath);

                var flags = Serializer.Instance.State.Settings.Flags;

                var count = Items.Count;

                Parallel.ForEach(Items, (GuidObject item) =>
                {
                    var path = Utils.PathCombine(folderPath, item.GetFileName() + ".sav");
                    var settings = new SerializationSettings(flags, item);
                    var bytes = Serializer.Instance.Serialize(item, settings);
                    FileSystemCache.WriteAllBytes(path, bytes);

                    oldFiles.Remove(path.ToLowerInvariant());
                });

                foreach (var subFolder in SubFolders.Values)
                {
                    subFolder.SaveToFolder(Utils.PathCombine(folderPath, subFolder.Name), oldFiles);
                }
            }

19 View Source File : ServerHelper.cs
License : MIT License
Project Creator : AmazingDM

public static void TestAllDelay()
            {
                if (_mux)
                    return;
                try
                {
                    _mux = true;
                    Parallel.ForEach(Global.Settings.Server, new ParallelOptions {MaxDegreeOfParallelism = 16},
                        server => { server.Test(); });
                    _mux = false;
                    TestDelayFinished?.Invoke(null, new EventArgs());
                }
                catch (Exception)
                {
                    // ignored
                }
            }

19 View Source File : ServerListTests.cs
License : GNU General Public License v3.0
Project Creator : Amebis

[TestMethod()]
        public void ServersNetworkTest()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;

            var xmlReader = XmlReader.Create(new MemoryStream(Encoding.UTF8.GetBytes(@"<ResourceRef Uri=""https://disco.eduvpn.org/v2/server_list.json"">
						<MinisignPublicKeyDictionary Key=""PublicKeys"">
							<PublicKey>RWRtBSX1alxyGX+Xn3LuZnWUT0w//B6EmTJvgaAxBMYzlQeI+jdrO6KF</PublicKey>
							<PublicKey>RWQKqtqvd0R7rUDp0rWzbtYPA3towPWcLDCl7eY9pBMMI/ohCmrS0WiM</PublicKey>
						</MinisignPublicKeyDictionary>
					</ResourceRef>")));
            while (xmlReader.ReadState == ReadState.Initial)
                xmlReader.Read();
            var source = new ResourceRef();
            source.ReadXml(xmlReader);

            // Load list of servers.
            var server_list_list_json = Xml.Response.Get(source);
            var server_list_list_ia = new ServerDictionary();
            server_list_list_ia.LoadJSON(server_list_list_json.Value);

            // Load all servers APIs.
            Parallel.ForEach(server_list_list_ia.Values, srv =>
            {
                var uriBuilder = new UriBuilder(srv.Base);
                uriBuilder.Path += "info.json";
                try
                {
                    new Models.ServerEndpoints().LoadJSON(Xml.Response.Get(uriBuilder.Uri).Value);
                }
                catch (AggregateException ex)
                {
                    if (ex.InnerException is WebException ex_web &&
                        (ex_web.Status == WebExceptionStatus.ConnectFailure || // connection refused
                        ex_web.Status == WebExceptionStatus.TrustFailure || // expired or invalid server certificate
                        ex_web.Status == WebExceptionStatus.SecureChannelFailure || // TLS failure
                        ex_web.Status == WebExceptionStatus.Timeout)) // server down
                    {
                        // Ignore connection failure WebException(s), as some servers are not publicly available or have other issues.
                    }
                    else
                        throw;
                }
            });

            // Re-load list of servers.
            server_list_list_json = Xml.Response.Get(
                res: source,
                previous: server_list_list_json);
        }

19 View Source File : Session.cs
License : GNU General Public License v3.0
Project Creator : Amebis

public void Run()
        {
            try
            {
                Parallel.ForEach(PreRun,
                    action =>
                    {
                        Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
                        try { action(); }
                        finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--)); }
                    });
            }
            catch (AggregateException ex)
            {
                var nonCancelledException = ex.InnerExceptions.Where(exInner => !(exInner is OperationCanceledException));
                if (nonCancelledException.Any())
                    throw new AggregateException("", nonCancelledException.ToArray());
                throw new OperationCanceledException();
            }

            DoRun();
            ConnectedTimeUpdater.Stop();
        }

19 View Source File : SelfUpdatePromptPage.cs
License : GNU General Public License v3.0
Project Creator : Amebis

public void CheckForUpdates()
        {
            try
            {
                Parallel.ForEach(new List<Action>()
                    {
                        () =>
                        {
                            // Get self-update.
                            var res = Properties.SettingsEx.Default.SelfUpdateDiscovery;
                            Trace.TraceInformation("Downloading self-update JSON discovery from {0}...", res.Uri.AbsoluteUri);
                            var obj = Properties.Settings.Default.ResponseCache.GetSeq(res, Window.Abort.Token);

                            var repoVersion = new Version((string)obj["version"]);
                            Trace.TraceInformation("Online version: {0}", repoVersion.ToString());
                            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => {
                                AvailableVersion = repoVersion;
                                Changelog = eduJSON.Parser.GetValue(obj, "changelog_uri", out string changelogUri) ? new Uri(changelogUri) : null;
                                Wizard.SelfUpdateProgressPage.DownloadUris = new List<Uri>(((List<object>)obj["uri"]).Select(uri => new Uri(res.Uri, (string)uri)));
                                Wizard.SelfUpdateProgressPage.Hash = ((string)obj["hash-sha256"]).FromHexToBin();
                                Wizard.SelfUpdateProgressPage.Arguments = eduJSON.Parser.GetValue(obj, "arguments", out string installerArguments) ? installerArguments : null;
                            }));
                        },

                        () =>
                        {
                            // Evaluate installed products.
                            Version productVersion = null;
                            var productId = Properties.Settings.Default.SelfUpdateBundleId.ToUpperInvariant();
                            Trace.TraceInformation("Evaluating installed products...");
                            using (var hklmKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
                            using (var uninstallKey = hklmKey.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", false))
                            {
                                foreach (var productKeyName in uninstallKey.GetSubKeyNames())
                                {
                                    Window.Abort.Token.ThrowIfCancellationRequested();
                                    using (var productKey = uninstallKey.OpenSubKey(productKeyName))
                                    {
                                        var bundleUpgradeCode = productKey.GetValue("BundleUpgradeCode");
                                        if ((bundleUpgradeCode is string   bundleUpgradeCodeString && bundleUpgradeCodeString.ToUpperInvariant() == productId ||
                                                bundleUpgradeCode is string[] bundleUpgradeCodeArray  && bundleUpgradeCodeArray.FirstOrDefault(code => code.ToUpperInvariant() == productId) != null) &&
                                            productKey.GetValue("BundleVersion") is string bundleVersionString)
                                        {
                                            // Our product entry found.
                                            productVersion = new Version(productKey.GetValue("DisplayVersion") is string displayVersionString ? displayVersionString : bundleVersionString);
                                            Trace.TraceInformation("Installed version: {0}", productVersion.ToString());
                                            break;
                                        }
                                    }
                                }
                            }
                            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => { InstalledVersion = productVersion; }));
                        },
                    },
                    action =>
                    {
                        Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
                        try { action(); }
                        finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--)); }
                    });
            }
            catch (AggregateException ex)
            {
                var nonCancelledException = ex.InnerExceptions.Where(innerException => !(innerException is OperationCanceledException));
                if (nonCancelledException.Any())
                    throw new AggregateException(Resources.Strings.ErrorSelfUpdateDetection, nonCancelledException.ToArray());
                throw new OperationCanceledException();
            }

            //// Mock the values for testing.
            //InstalledVersion = new Version(1, 0);
            //Properties.Settings.Default.SelfUpdateLastReminder = DateTime.MinValue;

            try
            {
                if (new Version(Properties.Settings.Default.SelfUpdateLastVersion) == AvailableVersion &&
                    (Properties.Settings.Default.SelfUpdateLastReminder == DateTime.MaxValue ||
                    (DateTime.UtcNow - Properties.Settings.Default.SelfUpdateLastReminder).TotalDays < 3))
                {
                    // We already prompted user for this version.
                    // Either user opted not to be reminded of this version update again,
                    // or it has been less than three days since the last prompt.
                    Trace.TraceInformation("Update deferred by user choice.");
                    return;
                }
            }
            catch { }

            if (InstalledVersion == null)
            {
                // Nothing to update.
                Trace.TraceInformation("Product not installed or version could not be determined.");
                return; // Quit self-updating.
            }

            if (AvailableVersion <= InstalledVersion)
            {
                // Product already up-to-date.
                Trace.TraceInformation("Update not required.");
                return;
            }

            // We're in the background thread - raise the prompt event via dispatcher.
            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
            {
                if (Wizard.NavigateTo.CanExecute(this))
                {
                    Properties.Settings.Default.SelfUpdateLastVersion = AvailableVersion.ToString();
                    Properties.Settings.Default.SelfUpdateLastReminder = DateTime.UtcNow;
                    Wizard.NavigateTo.Execute(this);
                }
            }));
        }

19 View Source File : RqqPeltSimulation.cs
License : MIT License
Project Creator : AndreyAkinshin

private List<double> RunSingle(RqqPeltChangePointDetector detector, IReadOnlyList<CpdTestData> dataSet, bool printReports)
        {
            int maxNameLength = dataSet.Select(data => data.Name.Length).Max();

            var penalties = new List<double>();

            Parallel.ForEach(dataSet, testData =>
            {
                var changePointIndexes = detector.GetChangePointIndexes(testData.Values.ToArray());
                var verification = CpdTestDataVerification.Verify(testData, changePointIndexes);
                lock (detector)
                {
                    penalties.Add(verification.Penalty);
                    PrintLine($"{testData.Name.PadRight(maxNameLength)} : {verification.Penalty}");
                    if (printReports)
                        PrintLine(verification.Report);
                }
            });

            PrintLine("  Sum  = " + penalties.Sum());
            PrintLine("  Max  = " + penalties.Max());
            foreach (double p in new[] {0.5, 0.90, 0.99})
            {
                string metric = $"P{p * 100}".PadRight(4);
                double estimate = HarrellDavisQuantileEstimator.Instance.GetQuantile(penalties, p);
                PrintLine($"  {metric} = {estimate:0.##}");
            }

            return penalties;
        }

19 View Source File : WikiBuildingDetailProvider.cs
License : MIT License
Project Creator : AnnoDesigner

private void SaveBuildingsDetailPage(WikiBuildingInfoPresets wikiBuildingInfoList)
        {
            Console.WriteLine("start fetching building details");

            if (!Directory.Exists(PathToDetailsFolder))
            {
                Directory.CreateDirectory(PathToDetailsFolder);
            }

            var existingMissingInfos = new List<string>();
            if (File.Exists(Path.Combine(PathToDetailsFolder, FILENAME_MISSING_INFOS)))
            {
                existingMissingInfos.AddRange(File.ReadAllLines(Path.Combine(PathToDetailsFolder, FILENAME_MISSING_INFOS), Encoding.UTF8));
            }

            var missingInfos = new List<string>();

            Stopwatch sw = new Stopwatch();
            sw.Start();

            Parallel.ForEach(wikiBuildingInfoList.Infos,
                new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
                curBuilding =>
                {
                    var pageName = curBuilding.Name.Replace(" ", "_");

                    //only download when not present and not forced to download
                    var fileName = GetCleanedFilename(pageName);
                    var destinationFilePath = Path.Combine(PathToDetailsFolder, $"{fileName}{FILE_ENDING_WIKITEXT}");
                    if (!Program.ForceDownload && (File.Exists(destinationFilePath) || existingMissingInfos.Contains(curBuilding.Name)))
                    {
                        return;
                    }

                    var provider = new WikiTextProvider();
                    var providerResult = provider.GetWikiTextAsync(pageName).GetAwaiter().GetResult();

                    if (!string.IsNullOrWhiteSpace(providerResult.WikiText))
                    {
                        providerResult.WikiText = GetLineBreakAlignedWikiText(providerResult.WikiText);
                        //align infobox name
                        providerResult.WikiText = providerResult.WikiText.Replace("{{Infobox_Buildings", "{{Infobox Buildings");
                        File.WriteAllText(destinationFilePath, providerResult.WikiText, Encoding.UTF8);
                        File.AppendAllLines(destinationFilePath, new List<string>
                        {
                            Environment.NewLine,
                            $"{REVISION_HEADER_ID}{REVISION_SEPARATOR}{providerResult.RevisionId}",
                            $"{REVISION_HEADER_DATE}{REVISION_SEPARATOR}{providerResult.EditDate:o}"
                        }, Encoding.UTF8);
                    }
                    else
                    {
                        missingInfos.Add(curBuilding.Name);
                    }
                });

            if (missingInfos.Count > 0)
            {
                File.WriteAllLines(Path.Combine(PathToDetailsFolder, FILENAME_MISSING_INFOS), missingInfos.Distinct().OrderBy(x => x), Encoding.UTF8);
            }

            sw.Stop();
            var message = $"finished fetching building details (took {sw.ElapsedMilliseconds} ms)";
            logger.Trace(message);
            Console.WriteLine(message);
        }

19 View Source File : XIVApi.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private List<Area> LoadTerritoryCore(string file)
        {
            if (!File.Exists(file))
            {
                return null;
            }

            var list = new List<Area>(2048);

            var lines = CSVParser.LoadFromPath(file, encoding: new UTF8Encoding(true));

            Parallel.ForEach(lines, (fields) =>
            {
                if (fields.Count < 5)
                {
                    return;
                }

                if (!int.TryParse(fields[0], out int id) ||
                    string.IsNullOrEmpty(fields[6]) ||
                    !int.TryParse(fields[10], out int indented) ||
                    !int.TryParse(fields[11], out int order))
                {
                    return;
                }

                if (id < AddtionalTerritoryStartID)
                {
                    return;
                }

                var entry = new Area()
                {
                    ID = id,
                    Name = fields[6],
                    IntendedUse = indented,
                    Order = order,
                };

                lock (list)
                {
                    list.Add(entry);
                }
            });

            return list;
        }

19 View Source File : XIVApi.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private void LoadArea()
        {
            if (!File.Exists(this.AreaFile))
            {
                return;
            }

            // 英語辞書として英語版リストをロードしておく
            var en = this.AreaENDictionary;

            var current = new List<Area>(256);

            var lines = CSVParser.LoadFromPath(this.AreaFile, encoding: new UTF8Encoding(true));

            Parallel.ForEach(lines, (fields) =>
            {
                if (fields.Count < 5)
                {
                    return;
                }

                if (!int.TryParse(fields[0], out int id) ||
                    string.IsNullOrEmpty(fields[4]))
                {
                    return;
                }

                var entry = new Area()
                {
                    ID = id,
                    NameEn = en[id]?.Name ?? string.Empty,
                    Name = fields[4]
                };

                lock (current)
                {
                    current.Add(entry);
                }
            });

            lock (this.areaList)
            {
                this.areaList.Clear();
                this.areaList.AddRange(current);
            }

            this.AppLogger.Trace($"xivapi area list loaded. {this.AreaFile}");
        }

19 View Source File : XIVApi.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private Dictionary<int, Area> LoadAreaEN()
        {
            var dic = new Dictionary<int, Area>()
            {
                { 0, new Area() {ID = 0, NameEn = "dummy", Name = "dummy"} }
            };

            if (!File.Exists(this.AreaENFile))
            {
                return dic;
            }

            var lines = CSVParser.LoadFromPath(this.AreaENFile, encoding: new UTF8Encoding(true));

            Parallel.ForEach(lines, (fields) =>
            {
                if (fields.Count < 5)
                {
                    return;
                }

                if (!int.TryParse(fields[0], out int id) ||
                    string.IsNullOrEmpty(fields[4]))
                {
                    return;
                }

                var entry = new Area()
                {
                    ID = id,
                    NameEn = fields[4],
                    Name = fields[4]
                };

                lock (dic)
                {
                    dic[entry.ID] = entry;
                }
            });

            this.AppLogger.Trace($"xivapi area list loaded. {this.AreaENFile}");

            return dic;
        }

19 View Source File : XIVApi.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private void LoadAction()
        {
            if (!File.Exists(this.SkillFile))
            {
                return;
            }

            var sw = Stopwatch.StartNew();

            var userList = this.UserActionList;

            var obj = new object();
            lock (this.actionList)
            {
                this.actionList.Clear();

                var lines = CSVParser.LoadFromPath(this.SkillFile, encoding: new UTF8Encoding(true));

                Parallel.ForEach(lines, (fields) =>
                {
                    if (fields.Count < 2)
                    {
                        return;
                    }

                    if (!uint.TryParse(fields[0], out uint id) ||
                        string.IsNullOrEmpty(fields[1]))
                    {
                        return;
                    }

                    var entry = new XIVApiAction()
                    {
                        ID = id,
                        Name = fields[1],
                        AttackTypeName = fields[XIVApiAction.AttackTypeIndex]
                    };

                    entry.SetAttackTypeEnum();

                    if (userList.ContainsKey(entry.ID))
                    {
                        entry.Name = userList[entry.ID].Name;
                    }

                    lock (obj)
                    {
                        this.actionList[entry.ID] = entry;
                    }
                });
            }

            sw.Stop();
            this.AppLogger.Trace($"xivapi action list loaded. {sw.Elapsed.TotalSeconds:N0}s {this.SkillFile}");
        }

19 View Source File : XIVApi.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private Dictionary<uint, XIVApiAction> LoadUserAction()
        {
            var list = new Dictionary<uint, XIVApiAction>(256);

            if (!File.Exists(this.UserSkillFile))
            {
                return list;
            }

            var lines = CSVParser.LoadFromPath(this.UserSkillFile, encoding: new UTF8Encoding(false));

            Parallel.ForEach(lines, (fields) =>
            {
                if (fields.Count < 2)
                {
                    return;
                }

                if (!uint.TryParse(fields[0], out uint id) ||
                    string.IsNullOrEmpty(fields[1]))
                {
                    return;
                }

                var entry = new XIVApiAction()
                {
                    ID = id,
                    Name = fields[1],
                };

                lock (list)
                {
                    list[entry.ID] = entry;
                }
            });

            this.AppLogger.Trace($"user action list loaded.");

            return list;
        }

19 View Source File : XIVApi.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private void LoadBuff()
        {
            if (!File.Exists(this.BuffFile))
            {
                return;
            }

            var lines = CSVParser.LoadFromPath(this.BuffFile, encoding: new UTF8Encoding(true));

            var obj = new object();
            lock (this.buffList)
            {
                this.buffList.Clear();

                Parallel.ForEach(lines, (fields) =>
                {
                    if (fields.Count < 2)
                    {
                        return;
                    }

                    uint id;
                    if (!uint.TryParse(fields[0], out id) ||
                        string.IsNullOrEmpty(fields[1]))
                    {
                        return;
                    }

                    var entry = new Buff()
                    {
                        ID = id,
                        Name = fields[1]
                    };

                    lock (obj)
                    {
                        this.buffList[entry.ID] = entry;
                    }
                });
            }

            this.AppLogger.Trace($"xivapi status list loaded. {this.BuffFile}");
        }

19 View Source File : MainViewModel.cs
License : MIT License
Project Creator : AntonyCorbett

private void ApplyMergeParameters()
        {
            Parallel.ForEach(Files, file =>
            {
                if (File.Exists(file.FilePath))
                {
                    MergePreparation.ApplyMergeParameters(
                        _backupFileService,
                        file.BackupFile.Database, 
                        file.MergeParameters);
                }
            });
        }

19 View Source File : PhysicSimulation.cs
License : Apache License 2.0
Project Creator : AntoineCharton

protected void UpdatePhysics(float dT)
        {
            lock (GetDynamicBodiesToRemoveID())
            {
                foreach(var body in GetDynamicBodiesToRemoveID())
                {
                    lock (GetBodiesData())
                    {
                        lock (Simulation)
                        {
                            Simulation.Bodies.Remove(body);
                        }
                        for (int i = 0; i < GetBodiesData().Count; i++)
                        {
                            if (GetBodiesData()[i].BodieID == body)
                            {
                                GetBodiesData().RemoveAt(i);
                            }
                        }
                    }
                }
                GetDynamicBodiesToRemoveID().Clear();
            }

            lock (GetStaticBodiesToRemoveID())
            {
                foreach (var body in GetStaticBodiesToRemoveID())
                {
                    lock (GetStaticBodiesData())
                    {
                        lock (Simulation)
                        {
                            Simulation.Statics.Remove(body);
                        }
                        for (int i = 0; i < GetStaticBodiesData().Count; i++)
                        {
                            if (GetStaticBodiesData()[i].BodieID == body)
                            {
                                GetStaticBodiesData().RemoveAt(i);
                            }
                        }
                    }
                }
                GetStaticBodiesToRemoveID().Clear();
            }

            UpdatePhysics(null, null, dT);
            lock (GetBodiesData())
            {
                Parallel.ForEach(GetBodiesData(), body =>
                {
                    if (Simulation.Bodies.BodyExists(body.BodieID))
                    {
                        Simulation.Bodies.GetDescription(body.BodieID, out var BodyDescription);
                        body.IsAddedToSimulation = true;
                        body.SetPosition(new Vector3(BodyDescription.Pose.Position.X, BodyDescription.Pose.Position.Y, BodyDescription.Pose.Position.Z));
                        body.SetRotation(new Quaternion(BodyDescription.Pose.Orientation.X, BodyDescription.Pose.Orientation.Y, BodyDescription.Pose.Orientation.Z, BodyDescription.Pose.Orientation.W));
                    }
                    else
                    {
                        body.IsAddedToSimulation = false;
                    }
                });
            }

            lock (GetAddedBodies())
            {
                foreach (var addedBody in GetAddedBodies())
                {
                    var id = BodiesFactory.AddBody(Simulation, addedBody.Position,
                        addedBody.Rotation,
                        addedBody.BodyType,
                        addedBody.BodyShape,
                        out bool isStatic,
                        addedBody.Mreplaced);

                    addedBody.PhysicObjectAddedToSimulation(id);
                }
                GetAddedBodies().Clear();
            }

            lock (GetAddedStaticBodies())
            {
                foreach (var addedBody in GetAddedStaticBodies())
                {
                    var id = BodiesFactory.AddBody(Simulation, addedBody.Position,
                        addedBody.Rotation,
                        addedBody.BodyType,
                        addedBody.BodyShape,
                        out bool isStatic,
                        addedBody.Mreplaced);
                    addedBody.PhysicObjectAddedToSimulation(id);
            
                }
                GetAddedStaticBodies().Clear();
            
            }
        }

19 View Source File : MainViewModel.cs
License : MIT License
Project Creator : AntonyCorbett

private void HandleDroppedFiles(DragEventArgs dragEventArgs)
        {
            var tmpFilesCollection = new ConcurrentBag<JwLibraryFile>();

            var jwLibraryFiles = _dragDropService.GetDroppedFiles(dragEventArgs);
                
            Parallel.ForEach(jwLibraryFiles, file =>
            {
                var backupFile = _backupFileService.Load(file);
                tmpFilesCollection.Add(new JwLibraryFile(file, backupFile));
            });

            foreach (var file in tmpFilesCollection)
            {
                if (Files.FirstOrDefault(x => IsSameFile(file.FilePath, x.FilePath)) == null)
                {
                    file.PropertyChanged += FilePropertyChanged;
                    Files.Add(file);
                }
            }
        }

19 View Source File : SlideArchiveEntryBatchHelper.cs
License : MIT License
Project Creator : AntonyCorbett

public IReadOnlyList<SlideArchiveEntry>? GetBatch()
        {
            var slideBatch = GetSlideBatch();
            if (slideBatch == null)
            {
                return null;
            }

            var result = new List<SlideArchiveEntry>();

            var map = new ConcurrentDictionary<Slide, BitmapSource>();

            Parallel.ForEach(slideBatch, slide =>
            {
                var image = GetImage(slide);
                if (image != null)
                {
                    map.TryAdd(slide, image);
                }
            });
            
            foreach (var slide in slideBatch)
            {
                result.Add(new SlideArchiveEntry
                {
                    ArchiveEntryName = slide.ArchiveEntryName,
                    Image = map[slide],
                });
            }

            return result;
        }

19 View Source File : MainViewModel.cs
License : MIT License
Project Creator : AntonyCorbett

private static async Task<ConcurrentDictionary<Slide, byte[]>> GenerateThumbnailsForBatch(
            IReadOnlyList<Slide> batch, Dictionary<string, byte[]> thumbnailCache)
        {
            var result = new ConcurrentDictionary<Slide, byte[]>();

            await Task.Run(() =>
            {
                Parallel.ForEach(batch, slide =>
                {
                    if (slide.OriginalFilePath != null)
                    {
                        if (!thumbnailCache.TryGetValue(slide.OriginalFilePath, out var thumbnailBytes))
                        {
                            // Note that we pad the thumbnails (so they are all identical sizes). If we don't,
                            // a WPF Presentation rendering issue causes an OutOfMemoryException.
                            thumbnailBytes = GraphicsUtils.GetRawImageAutoRotatedAndResized(
                                slide.OriginalFilePath, ThumbnailWidth, ThumbnailHeight);
                        }

                        if (thumbnailBytes != null)
                        {
                            result.TryAdd(slide, thumbnailBytes);
                        }
                    }
                });
            });

            return result;
        }

19 View Source File : DragDropService.cs
License : MIT License
Project Creator : AntonyCorbett

private void OnDragDrop(DragDropMessage message)
        {
            var epubFolder = FileUtils.GetEpubFolder();
            if (!FileUtils.DirectoryIsWritable(epubFolder))
            {
                message.DragEventArgs.Handled = true;
                _snackbarService.EnqueueWithOk(string.Format(Properties.Resources.NO_WRITE_ACCESS, epubFolder));
                return;
            }

            var busyCursor = _userInterfaceService.GetBusy();

            var origEpubPath = _bibleVersesService.EpubPath;

            Task.Run(() =>
            {
                var files = GetDroppedFiles(message.DragEventArgs);

                var validFileCount = 0;

                // close reader so that we can overwrite the current epub (if necessary)
                _bibleVersesService.CloseReader();

                Parallel.ForEach(files, file =>
                {
                    try
                    {
                        if (_bibleVersesService.IsValidBibleEpub(file))
                        {
                            File.Copy(file, GetDestinationFileName(file), overwrite: true);
                            Interlocked.Increment(ref validFileCount);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Logger.Error(ex, [email protected]"Could not copy epub file {file}");
                    }
                });

                _snackbarService.EnqueueWithOk(GetDoneMessage(files.Count, validFileCount));
                message.DragEventArgs.Handled = true;
            }).ContinueWith(t =>
            {
                _bibleVersesService.EpubPath = origEpubPath;

                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    EpubFileListChanged?.Invoke(this, EventArgs.Empty);
                    busyCursor.Dispose();
                });
            });
        }

19 View Source File : MSBPRDependencyGraph.cs
License : MIT License
Project Creator : aolszowka

internal static Dictionary<string, IEnumerable<string>> ResolvereplacedemblyReferenceDependencies(IEnumerable<string> targetProjects)
        {
            ConcurrentBag<KeyValuePair<string, IEnumerable<string>>> resolvedreplacedemblyReferences = new ConcurrentBag<KeyValuePair<string, IEnumerable<string>>>();

            // Because of the large number of projects that could be scanned perform this in parallel.
            Parallel.ForEach(targetProjects, targetProject =>
            {
                IEnumerable<string> currentProjectreplacedemblyReferences = MSBuildUtilities.replacedemblyReferences(targetProject);
                KeyValuePair<string, IEnumerable<string>> currentResult = new KeyValuePair<string, IEnumerable<string>>(targetProject, currentProjectreplacedemblyReferences);
                resolvedreplacedemblyReferences.Add(currentResult);
            }
            );

            // Convert this into the Dictionary
            Dictionary<string, IEnumerable<string>> result = new Dictionary<string, IEnumerable<string>>();
            foreach (KeyValuePair<string, IEnumerable<string>> kvp in resolvedreplacedemblyReferences)
            {
                result.Add(kvp.Key, kvp.Value);
            }

            return result;
        }

19 View Source File : MSBPRDependencyGraph.cs
License : MIT License
Project Creator : aolszowka

internal static Dictionary<string, IEnumerable<string>> ResolvePackageReferenceDependencies(IEnumerable<string> targetProjects)
        {
            ConcurrentBag<KeyValuePair<string, IEnumerable<string>>> resolvedPackageReferences = new ConcurrentBag<KeyValuePair<string, IEnumerable<string>>>();

            // Because of the large number of projects that could be scanned perform this in parallel.
            Parallel.ForEach(targetProjects, targetProject =>
            {
                IEnumerable<string> currentProjectPackageReferences = MSBuildUtilities.PackageReferences(targetProject);
                KeyValuePair<string, IEnumerable<string>> currentResult = new KeyValuePair<string, IEnumerable<string>>(targetProject, currentProjectPackageReferences);
                resolvedPackageReferences.Add(currentResult);
            }
            );

            // Convert this into the Dictionary
            Dictionary<string, IEnumerable<string>> result = new Dictionary<string, IEnumerable<string>>();
            foreach (KeyValuePair<string, IEnumerable<string>> kvp in resolvedPackageReferences)
            {
                result.Add(kvp.Key, kvp.Value);
            }

            return result;
        }

See More Examples