public void Logout() { var(name, callback) = users.AsEnumerable() .Where(e => e.Value == Callback) .Select(entry => (entry.Key, entry.Value)) .First(); users.Remove(name); users.AsParallel() .ForAll(entry => entry.Value.OnRemoveUser(name)); callback.OnExit(); }
private void ReduceIndirectCoords(IDictionary <int, float[]> matrix, int totalCoords) { if (_maxIndirectPercentage >= 100) { return; } var numDirectCoords = matrix.Values.Sum(row => row.Count(coord => coord >= 1)); var numIndirectCoords = matrix.AsParallel().Sum(row => row.Value.Count(coord => coord > 0 && coord < 1)); var maxAllowedIndirectCoords = (int)((totalCoords - numDirectCoords) * _maxIndirectPercentage); if (numIndirectCoords > maxAllowedIndirectCoords) { var minAllowedIndirectCoord = matrix .SelectMany(row => row.Value.Where(coord => coord > 0 && coord < 1)) .NthLargest(maxAllowedIndirectCoords); foreach (var row in matrix.Values) { for (var i = 0; i < row.Length; ++i) { if (row[i] < minAllowedIndirectCoord) { row[i] = 0; } } } } }
public static IDictionaryChangeResult <TKey> CompareTo <TKey, TValue>(this IDictionary <TKey, TValue> local, IDictionary <TKey, TValue> remote) { if (local == null) { throw new ArgumentNullException("local"); } if (remote == null) { throw new ArgumentNullException("remote"); } var changed = new List <TKey>(local.Count()); var deleted = new List <TKey>(local.Count()); Parallel.ForEach(local, localItem => { /* Check if primary key exists in both local and remote * and if so check if changed, if not it has been deleted */ TValue changeCandidate; if (remote.TryGetValue(localItem.Key, out changeCandidate) ) // Enthält nach dem Beenden dieser Methode den Wert, der dem angegebenen Schlüssel zugeordnet ist { // changeCanditate = meta des remote posts // wenn der meta von remote und der meta von lokal gleich sind, dann keine Änderung if (localItem.Value.Equals(changeCandidate)) { return; } lock (changed) { changed.Add(localItem.Key); } } else { lock (deleted) { deleted.Add(localItem.Key); } } }); var inserted = remote .AsParallel() .Where(x => !local.ContainsKey(x.Key)) .Select(x => x.Key) .ToList(); return(new IDictionaryChangeResult <TKey>(deleted, changed, inserted)); }
private static void AddMetric(IDictionary <string, double> metrics) { if (metrics != null) { metrics.AsParallel().ForAll(m => { NRClient.AddCustomParameter(m.Key, m.Value); }); } }
private static void AddProperties(IDictionary <string, string> properties) { if (properties != null) { properties.AsParallel().ForAll(p => { NRClient.AddCustomParameter(p.Key, p.Value); }); } }
private static void AddMetric(IDictionary<string, double> metrics) { if (metrics != null) { metrics.AsParallel().ForAll(m => { NRClient.AddCustomParameter(m.Key, m.Value); }); } }
internal Task RunActionsAsync(Action <EasyEventInvoker> action) { return(Task.Factory.StartNew(() => { if (action == null) { return; } easyEventsContainer.AsParallel().ForAll(item => { action?.Invoke(item.Value); }); }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); }
private void InitializeMappings() { using (ILogMethod method = Log.LogMethod(this.DYN_MODULE_NAME, "InitializeMappings")) { IDictionary <string, IMonitorHandler> handlerInstances = null; try { _handlerMappings = new StringDictionary <IMonitorHandler>(); handlerInstances = new StringDictionary <IMonitorHandler>(); foreach (var mappingType in _handlerMappingTypes.AsParallel()) { MonitorHandlerBase handler = null; string mappingTypeKey = mappingType.Value.FullName; if (handlerInstances.ContainsKey(mappingTypeKey)) { handler = handlerInstances[mappingTypeKey] as MonitorHandlerBase; } else { handler = Activator.CreateInstance(mappingType.Value, true) as MonitorHandlerBase; handlerInstances.Add(mappingTypeKey, handler); } if (handler == null) { continue; } if (!_handlerMappings.ContainsKey(mappingType.Key)) { _handlerMappings.Add(mappingType.Key, handler); } } const string faultKey = "-1_-1"; _faultHandler = _handlerMappings[faultKey]; } catch (Exception ex) { method.Exception(ex); } finally { if (handlerInstances != null) { handlerInstances.Clear(); handlerInstances = null; } } } }
private static IDictionary <int, IAdjacencyMatrix> CalculateAdjacencyMatrices(IDictionary <string, IDictionary <IBitVector, IReadOnlyCollection <IBitVector> > > punchedCardsCollection) { return(punchedCardsCollection .AsParallel() .SelectMany(punchedCardsCollectionItem => punchedCardsCollectionItem.Value .Select(label => new Tuple <int, IAdjacencyMatrix>( GetAdjacencyMatrixKey(punchedCardsCollectionItem.Key, label.Key), new AdjacencyMatrix(label.Value)))) .ToDictionary(t => t.Item1, t => t.Item2)); }
public decimal CalculatePostingValue(DateTime fromDate, DateTime toDate, int?sortOrder = null) { if (fromDate.Date > toDate.Date) { return(0M); } decimal postingValue; string dateIntervalKey = ToDateIntervalKey(fromDate, toDate); if (sortOrder.HasValue == false) { if (_postingValueForDateIntervalDictionary.TryGetValue(dateIntervalKey, out postingValue)) { return(postingValue); } } IDictionary <int, decimal> postingValueForYearMonthDictionary = GetPostingValueForYearMonthDictionary(); if (IsSameYearMonth(fromDate, toDate)) { if (IsFullMonth(fromDate, toDate) == false || sortOrder.HasValue) { return(HandleCalculatedPostingValue(dateIntervalKey, Between(fromDate, toDate, sortOrder).AsParallel().Sum(postingLine => postingLine.PostingValue), sortOrder)); } return(HandleCalculatedPostingValue(dateIntervalKey, ResolvePostingValue(postingValueForYearMonthDictionary, ToYearMonthKey(toDate)), null)); } postingValue = IsFirstDayInMonth(fromDate) ? ResolvePostingValue(postingValueForYearMonthDictionary, ToYearMonthKey(fromDate)) : Between(fromDate, ToLastDayInMonth(fromDate), null) .AsParallel() .Sum(postingLine => postingLine.PostingValue); int fromYearMonthKey = ToYearMonthKey(ToFirstDayInMonth(fromDate).AddMonths(1)); int toYearMonthKey = ToYearMonthKey(ToFirstDayInMonth(toDate).AddMonths(-1)); postingValue += postingValueForYearMonthDictionary .AsParallel() .Where(item => item.Key >= fromYearMonthKey && item.Key <= toYearMonthKey) .Sum(item => item.Value); postingValue += IsLastDayInMonth(toDate) && sortOrder.HasValue == false ? ResolvePostingValue(postingValueForYearMonthDictionary, ToYearMonthKey(toDate)) : Between(ToFirstDayInMonth(toDate), toDate, sortOrder) .AsParallel() .Sum(postingLine => postingLine.PostingValue); return(HandleCalculatedPostingValue(dateIntervalKey, postingValue, sortOrder)); }
private void AddMissingValuesToConfiguration(IDictionary <string, string> configuration) { defaultConfig.AsParallel().ForAll(element => { if (!configuration.ContainsKey(element.Key)) { configuration.Add(element.Key, element.Value); } else if (string.IsNullOrWhiteSpace(configuration[element.Key])) { configuration[element.Key] = element.Value; } }); }
/// <summary> /// Identify the N-Order Projects which Depend on this Project. /// </summary> /// <param name="targetProject">The project for which to identify projects that depend on it.</param> /// <param name="dependencyGraph">A Dependency Graph where the Key is the Project and the Value is the Direct References of that project.</param> /// <returns></returns> /// <remarks> /// It is helpful to think of this as returning a list of projects /// which, if this project were modified, would need to be rebuilt. /// </remarks> internal static HashSet <string> GenerateNOrderDependsOnMe(string targetProject, IDictionary <string, SortedSet <string> > dependencyGraph) { HashSet <string> result = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase); if (!dependencyGraph.ContainsKey(targetProject)) { string exception = $"Could not find project `{targetProject}` in given dictionary."; throw new NotSupportedException(exception); } Stack <string> resolver = new Stack <string>(); resolver.Push(targetProject); while (resolver.Count != 0) { string currentDependency = resolver.Pop(); if (result.Contains(currentDependency)) { // Do not attempt to resolve something that has already been resolved } else { // First add the dependency to the list of resolved result.Add(currentDependency); // Now spin though the entire list looking for projects to push ParallelQuery <string> currentDependsOnMe = dependencyGraph .AsParallel() .Where(kvp => kvp.Value.Contains(currentDependency)) .Select(kvp => kvp.Key); // Resolve these "recursively" foreach (string directDependency in currentDependsOnMe) { resolver.Push(directDependency); } } } return(result); }
private void AddMetric(IDictionary <string, double> metrics) { try { if (metrics != null) { metrics.AsParallel().ForAll(m => { if (!Metrics.ContainsKey(m.Key)) { AddMetric(m.Key); } }); } } catch (Exception ex) { logger.TrackException(ex); throw; } }
private bool QueryPointcut <TPointcut, TItem>( ILogWriter logger, IDictionary <AssemblyDefinition, TypeDefinition[]> asmTypes, KeyValuePair <PointcutExpression, IPointcut> pointcut, Func <TypeDefinition[], TPointcut, IEnumerable <TItem> > queryAction, Func <IEnumerable <TItem>, IEnumerable <CodeTree.TypeNode> > createTypeNodes ) where TPointcut : class, IPointcut { var tPointcut = pointcut.Value as TPointcut; if (tPointcut == null) { return(false); } Dictionary <AssemblyDefinition, TItem[]> filteredAsmTypes; try { logger.Append("STARTED: executing pointcut '{0}'...", tPointcut.Name); filteredAsmTypes = asmTypes.AsParallel().ToDictionary( asmType => asmType.Key, asmType => queryAction(asmType.Value, tPointcut).ToArray()); logger.Append("COMPLETED: executing pointcut '{0}'", tPointcut.Name); } catch (Exception e) { logger.Append("ERROR executing pointcut '{0}'. Reason: '{1}'", tPointcut.Name, e.Message); filteredAsmTypes = asmTypes.ToDictionary(x => x.Key, x => new TItem[0]); } _treeDispatcher.BeginInvoke(new Action(() => _result.AddPointcut(tPointcut, string.Format("[{0}(\"{1}\")]", pointcut.Key.AttributeName, pointcut.Key.Saql), filteredAsmTypes.Select(x => new CodeTree.AssemblyNode(x.Key, createTypeNodes(x.Value)))))); return(true); }
private void ProcessAllUncommitEventMessageBeforeEventStoreDispatcherStartUp() { var _factory = new ConnectionFactory(); _factory.Uri = dispatcherSetting.RabbitMqConnectString; _factory.AutomaticRecoveryEnabled = true; var connection = _factory.CreateConnection(); var channelCounter = dispatcherSetting.QueuePoolSize; while (channelCounter > 0) { var itemNo = channelCounter - 1; var channel = connection.CreateModel(); var queueName = MQ_QUEUE_NAME + itemNo; channel.ExchangeDeclare(MQ_EXCHANAGE_NAME, ExchangeType.Direct, true, false, null); channel.QueueDeclare(queueName, true, false, false, null); channel.QueueBind(MQ_EXCHANAGE_NAME, queueName, string.Empty); var consumer = new EventMessageConsumer(channel, ProcessEventMessageOnStartUp, ProcessEventMessageFailed); channel.BasicQos(0, 1, false); channel.BasicConsume(queueName, false, consumer); tmpconsumerChannelDic.Add(queueName, new Tuple <IModel, EventMessageConsumer>(channel, consumer)); } Task.Factory.StartNew(() => { this.GetLogger("EventStoreDispatcherStartUp").Info("waiting proccess uncommit event message at {0}", DateTime.Now); while (slim.CurrentCount < dispatcherSetting.QueuePoolSize) { Task.Delay(1000).Wait(); } this.GetLogger("EventStoreDispatcherStartUp").Info("proccess uncommit event message end at {0}", DateTime.Now); }).Wait(); tmpconsumerChannelDic.AsParallel().ForAll(cc => cc.Value.Item1.Close()); tmpconsumerChannelDic.Clear(); }
public IObservable<WebResponse> HttpRequest(string url, IDictionary<string, string> postData, Encoding enc, IEnumerable<IPostFile> postFiles) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.Credentials = Credentials; req.CookieContainer = Cookie; if (postData != null) { return Observable.Using(() => new PostFileData(), _ => new[] { _ }.ToObservable() .ObserveOn(Scheduler.TaskPool) .Do(post => req.ContentType = "multipart/form-data; boundary=" + post.Boundary) .Do(post => postData.AsParallel().ForAll(line => post.Add(line.Key, line.Value)) ) .Do(post => postFiles.AsParallel().ForAll(postFile => post.Add(postFile))) .Select(post => post.ToBytes())) .Do(data => { req.ContentLength = data.Length; }) .Do(data => req.GetRequestStreamAsObserverable() .DisposeSubscribe(stream => stream.Write(data, 0, data.Length) , ex => { throw ex; })) .SelectMany(_ => req.GetResponseAsObserverable()); } else { return req.GetResponseAsObserverable(); } }
private void InitializeTgtParserMappingsH2G() { using (ILogMethod method = Log.LogMethod(this.DYN_MODULE_NAME, "InitializeMappings")) { IDictionary <string, IMonTgtParser> parserInstances = null; try { _tgtParserMappingsH2G = new StringDictionary <IMonTgtParser>(); _tgtParserMappingsByTypeH2G = new StringDictionary <IMonTgtParser>(); _monitorTypeAttributesH2G = new StringDictionary <MonTgtParserMappingAttribute>(); parserInstances = new StringDictionary <IMonTgtParser>(); foreach (var mappingType in _tgtParserMappingTypesH2G.AsParallel()) { IMonTgtParser parser = null; MappingTypeH2GInfo typeInfo = mappingType.Value; MonTgtParserMappingH2GAttribute attr = typeInfo.MappingAttribute; string mappingTypeKey = typeInfo.MappingType.FullName; if (parserInstances.ContainsKey(mappingTypeKey)) { parser = parserInstances[mappingTypeKey] as IMonTgtParser; } else { parser = Activator.CreateInstance(typeInfo.MappingType) as IMonTgtParser; if (parser != null) { parser.MappingAttributeH2G = typeInfo.MappingAttribute; parserInstances.Add(mappingTypeKey, parser); } } if (parser == null) { continue; } if (!_tgtParserMappingsH2G.ContainsKey(attr.FaultSourceTypeKey)) { _tgtParserMappingsH2G.Add(attr.FaultSourceTypeKey, parser); } if (attr.MonitorTargetType != null) { if (!_tgtParserMappingsByTypeH2G.ContainsKey(attr.MonitorTargetType.FullName)) { _tgtParserMappingsByTypeH2G.Add(attr.MonitorTargetType.FullName, parser); } string monitorKey = attr.MonitorTargetType.Name; if (!_monitorTypeAttributesH2G.ContainsKey(monitorKey)) { _monitorTypeAttributesH2G.Add(monitorKey, attr); } } } } catch (Exception ex) { method.Exception(ex); } finally { if (parserInstances != null) { parserInstances.Clear(); parserInstances = null; } } } }
private static void AddProperties(IDictionary<string, string> properties) { if (properties != null) { properties.AsParallel().ForAll(p => { NRClient.AddCustomParameter(p.Key, p.Value); }); } }
public IList <int> IterateByDictionaryInParallel() => _dictionary.AsParallel().Where(x => _filter.Contains(x.Key)).Select(x => x.Value).ToList();