public void ProbingCompleted(ClusterInfo cluster, IReadOnlyList <DestinationProbingResult> probingResults) { if (probingResults.Count == 0) { return; } var threshold = GetFailureThreshold(cluster); var newHealthStates = new NewActiveDestinationHealth[probingResults.Count]; for (var i = 0; i < probingResults.Count; i++) { var destination = probingResults[i].Destination; var count = _failureCounters.GetOrCreateValue(destination); var newHealth = EvaluateHealthState(threshold, probingResults[i].Response, count); newHealthStates[i] = new NewActiveDestinationHealth(destination, newHealth); } _healthUpdater.SetActive(cluster, newHealthStates); }
public void GetOrCreateValue () { var cwt = new ConditionalWeakTable <object,object> (); try { cwt.GetOrCreateValue (null); Assert.Fail ("#0"); } catch (ArgumentNullException) {} object key = "foo"; object val = cwt.GetOrCreateValue (key); Assert.IsTrue (val != null, "#2"); Assert.AreEqual (typeof (object), val.GetType () , "#3"); Assert.AreEqual (val, cwt.GetOrCreateValue (key), "#4"); var cwt2 = new ConditionalWeakTable <object, string> (); try { cwt2.GetOrCreateValue (key); Assert.Fail ("#5"); } catch (MissingMethodException) {} }
/// <summary> /// Returns the topmost <see cref="IBlockOperation"/> for given <paramref name="method"/>. /// </summary> public static IBlockOperation GetTopmostOperationBlock(this IMethodSymbol method, Compilation compilation, CancellationToken cancellationToken = default) { var methodToBlockMap = s_methodToTopmostOperationBlockCache.GetOrCreateValue(compilation); return(methodToBlockMap.GetOrAdd(method, ComputeTopmostOperationBlock)); // Local functions. IBlockOperation ComputeTopmostOperationBlock(IMethodSymbol unused) { if (!Equals(method.ContainingAssembly, compilation.Assembly)) { return(null); } foreach (var decl in method.DeclaringSyntaxReferences) { var syntax = decl.GetSyntax(cancellationToken); // VB Workaround: declaration.GetSyntax returns StatementSyntax nodes instead of BlockSyntax nodes // GetOperation returns null for StatementSyntax, and the method's operation block for BlockSyntax. if (compilation.Language == LanguageNames.VisualBasic) { syntax = syntax.Parent; } var semanticModel = compilation.GetSemanticModel(syntax.SyntaxTree); foreach (var descendant in syntax.DescendantNodesAndSelf()) { var operation = semanticModel.GetOperation(descendant, cancellationToken); if (operation is IBlockOperation blockOperation) { return(blockOperation); } } } return(null); } }
internal static bool IsGenerated(this SyntaxTree tree, GeneratedCodeRecognizer generatedCodeRecognizer, Compilation compilation) { if (tree == null) { return(false); } //this is locking if the compilation is not present in the Cache. var cache = Cache.GetOrCreateValue(compilation); if (cache.TryGetValue(tree, out var result)) { return(result); } var generated = generatedCodeRecognizer.IsGenerated(tree); cache.TryAdd(tree, generated); return(generated); }
public SkippedHostAnalyzersInfo GetSkippedAnalyzersInfo(Project project, DiagnosticAnalyzerInfoCache infoCache) { var box = _skippedHostAnalyzers.GetOrCreateValue(project.AnalyzerReferences); if (box.Value != null && box.Value.TryGetValue(project.Language, out var info)) { return(info); } lock (box) { box.Value ??= ImmutableDictionary <string, SkippedHostAnalyzersInfo> .Empty; if (!box.Value.TryGetValue(project.Language, out info)) { info = SkippedHostAnalyzersInfo.Create(this, project.AnalyzerReferences, project.Language, infoCache); box.Value = box.Value.Add(project.Language, info); } return(info); } }
public static void GetValueTest() { ConditionalWeakTable<object, object> cwt = new ConditionalWeakTable<object, object>(); object key = new object(); object obj = null; object value = cwt.GetValue(key, k => new object()); Assert.True(cwt.TryGetValue(key, out value)); Assert.Equal(value, cwt.GetOrCreateValue(key)); WeakReference<object> wrValue = new WeakReference<object>(value, false); WeakReference<object> wrkey = new WeakReference<object>(key, false); key = null; value = null; GC.Collect(); // key and value must be collected Assert.False(wrValue.TryGetTarget(out obj)); Assert.False(wrkey.TryGetTarget(out obj)); }
public static Option <string[]> TryGetFilterLabels(this IGraphElementModel model, Type type, FilterLabelsVerbosity filterLabelsVerbosity) { var labels = DerivedLabels .GetOrCreateValue(model) .GetOrAdd( type, closureType => { return(model.Metadata .Where(kvp => !kvp.Key.IsAbstract && closureType.IsAssignableFrom(kvp.Key)) .Select(kvp => kvp.Value.Label) .OrderBy(x => x) .ToArray()); }); return(labels.Length == 0 ? default(Option <string[]>) : labels.Length == model.Metadata.Count && filterLabelsVerbosity == FilterLabelsVerbosity.Minimum ? Array.Empty <string>() : labels); }
public static void Add(int numObjects) { // Isolated to ensure we drop all references even in debug builds where lifetime is extended by the JIT to the end of the method Func <int, Tuple <ConditionalWeakTable <object, object>, WeakReference[], WeakReference[]> > body = count => { object[] keys = Enumerable.Range(0, count).Select(_ => new object()).ToArray(); object[] values = Enumerable.Range(0, count).Select(_ => new object()).ToArray(); var cwt = new ConditionalWeakTable <object, object>(); for (int i = 0; i < count; i++) { cwt.Add(keys[i], values[i]); } for (int i = 0; i < count; i++) { object value; Assert.True(cwt.TryGetValue(keys[i], out value)); Assert.Same(values[i], value); Assert.Same(value, cwt.GetOrCreateValue(keys[i])); Assert.Same(value, cwt.GetValue(keys[i], _ => new object())); } return(Tuple.Create(cwt, keys.Select(k => new WeakReference(k)).ToArray(), values.Select(v => new WeakReference(v)).ToArray())); }; Tuple <ConditionalWeakTable <object, object>, WeakReference[], WeakReference[]> result = body(numObjects); GC.Collect(); Assert.NotNull(result.Item1); for (int i = 0; i < numObjects; i++) { Assert.False(result.Item2[i].IsAlive, $"Expected not to find key #{i}"); Assert.False(result.Item3[i].IsAlive, $"Expected not to find value #{i}"); } }
public static void GetValue() { var cwt = new ConditionalWeakTable <object, object>(); var key = new object(); object obj = null; object value = cwt.GetValue(key, k => new object()); Assert.True(cwt.TryGetValue(key, out value)); Assert.Equal(value, cwt.GetOrCreateValue(key)); WeakReference <object> wrValue = new WeakReference <object>(value, false); WeakReference <object> wrkey = new WeakReference <object>(key, false); key = null; value = null; GC.Collect(); // key and value must be collected Assert.False(wrValue.TryGetTarget(out obj)); Assert.False(wrkey.TryGetTarget(out obj)); }
/// <summary> /// Gets the registered service for specified data presenter. /// </summary> /// <typeparam name="T">Type of service.</typeparam> /// <param name="dataPresenter">The data presenter.</param> /// <param name="autoCreate">Indicates whether service implementation should be created automatically.</param> /// <returns>The service.</returns> public static T GetRegisteredService <T>(this DataPresenter dataPresenter, bool autoCreate = true) where T : class, IService { if (dataPresenter == null) { throw new ArgumentNullException(nameof(dataPresenter)); } if (autoCreate) { var servicesByType = _services.GetOrCreateValue(dataPresenter); return((T)servicesByType.GetOrAdd(typeof(T), type => CreateService <T>(dataPresenter))); } else if (_services.TryGetValue(dataPresenter, out var servicesByType)) { if (servicesByType.ContainsKey(typeof(T))) { return((T)servicesByType[typeof(T)]); } } return(null); }
private async Task <HostCompilationStartAnalysisScope> GetCompilationAnalysisScopeAsync( DiagnosticAnalyzer analyzer, HostSessionStartAnalysisScope sessionScope, AnalyzerExecutor analyzerExecutor) { var analyzerAndOptions = new AnalyzerAndOptions(analyzer, analyzerExecutor.AnalyzerOptions); try { return(await GetCompilationAnalysisScopeCoreAsync(analyzerAndOptions, sessionScope, analyzerExecutor).ConfigureAwait(false)); } catch (OperationCanceledException) { // Task to compute the scope was cancelled. // Clear the entry in scope map for analyzer, so we can attempt a retry. var compilationActionsMap = _compilationScopeMap.GetOrCreateValue(analyzerExecutor.Compilation); Task <HostCompilationStartAnalysisScope> cancelledTask; compilationActionsMap.TryRemove(analyzerAndOptions, out cancelledTask); analyzerExecutor.CancellationToken.ThrowIfCancellationRequested(); return(await GetCompilationAnalysisScopeAsync(analyzer, sessionScope, analyzerExecutor).ConfigureAwait(false)); } }
public static void Add(int numObjects) { // Isolated to ensure we drop all references even in debug builds where lifetime is extended by the JIT to the end of the method Func<int, Tuple<ConditionalWeakTable<object, object>, WeakReference[], WeakReference[]>> body = count => { object[] keys = Enumerable.Range(0, count).Select(_ => new object()).ToArray(); object[] values = Enumerable.Range(0, count).Select(_ => new object()).ToArray(); var cwt = new ConditionalWeakTable<object, object>(); for (int i = 0; i < count; i++) { cwt.Add(keys[i], values[i]); } for (int i = 0; i < count; i++) { object value; Assert.True(cwt.TryGetValue(keys[i], out value)); Assert.Same(values[i], value); Assert.Same(value, cwt.GetOrCreateValue(keys[i])); Assert.Same(value, cwt.GetValue(keys[i], _ => new object())); } return Tuple.Create(cwt, keys.Select(k => new WeakReference(k)).ToArray(), values.Select(v => new WeakReference(v)).ToArray()); }; Tuple<ConditionalWeakTable<object, object>, WeakReference[], WeakReference[]> result = body(numObjects); GC.Collect(); Assert.NotNull(result.Item1); for (int i = 0; i < numObjects; i++) { Assert.False(result.Item2[i].IsAlive, $"Expected not to find key #{i}"); Assert.False(result.Item3[i].IsAlive, $"Expected not to find value #{i}"); } }
public Authorization Authenticate(string challenge, WebRequest webRequest, ICredentials credentials) { if (credentials == null || challenge == null) { return(null); } string header = challenge.Trim(); int idx = header.ToLower().IndexOf("ntlm"); if (idx == -1) { return(null); } idx = header.IndexOfAny(new char [] { ' ', '\t' }); if (idx != -1) { header = header.Substring(idx).Trim(); } else { header = null; } HttpWebRequest request = webRequest as HttpWebRequest; if (request == null) { return(null); } lock (cache) { var ds = cache.GetOrCreateValue(request); return(ds.Authenticate(header, webRequest, credentials)); } }
private Task HandleCodingConventionsChangedAsync(DocumentId documentId, object sender, CodingConventionsChangedEventArgs e) { var projectId = documentId.ProjectId; var projectsAlreadyNotified = s_projectNotifications.GetOrCreateValue(e); lock (projectsAlreadyNotified) { if (!projectsAlreadyNotified.Add(projectId)) { return(Task.CompletedTask); } } var diagnosticAnalyzerService = ((IMefHostExportProvider)_workspace.Services.HostServices).GetExports <IDiagnosticAnalyzerService>().Single().Value; var foregroundNotificationService = ((IMefHostExportProvider)_workspace.Services.HostServices).GetExports <IForegroundNotificationService>().Single().Value; foregroundNotificationService.RegisterNotification(UpdateProject, _listener.BeginAsyncOperation(nameof(HandleCodingConventionsChangedAsync)), CancellationToken.None); return(Task.CompletedTask); void UpdateProject() { if (!_workspace.CurrentSolution.ContainsProject(projectId)) { // The project or solution was closed before running this update. return; } // Send a notification that project options have changed. This ensures the options used by commands, // e.g. Format Document, are correct following a change to .editorconfig. Unlike a change to compilation // or parse options, this does not discard the syntax and semantics already gathered for the solution. _workspace.OnProjectOptionsChanged(projectId); // Request diagnostics be run on the project again. diagnosticAnalyzerService.Reanalyze(_workspace, SpecializedCollections.SingletonEnumerable(projectId)); } }
private static View?GetCachedControl(string?propertyName, object rootView, Func <View?> fetchControlFromView) { if (propertyName == null) { throw new ArgumentNullException(nameof(propertyName)); } if (fetchControlFromView is null) { throw new ArgumentNullException(nameof(fetchControlFromView)); } var ourViewCache = viewCache.GetOrCreateValue(rootView); if (ourViewCache.TryGetValue(propertyName, out View? ret)) { return(ret); } ret = fetchControlFromView(); ourViewCache.Add(propertyName, ret); return(ret); }
public void BasicAddThenGetOrCreateValue(K[] keys, V[] values) { ConditionalWeakTable <K, V> tbl = new ConditionalWeakTable <K, V>(); // assume additions for all values for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } for (int i = 0; i < keys.Length; i++) { V val; // make sure GetOrCreateValues the value added (and not a new object) val = tbl.GetOrCreateValue(keys[i]); if (val == null || !val.Equals(values[i])) { // only one of the values is null or the values don't match Test.Eval(false, "Err_020 The value returned by GetOrCreateValue doesn't match the object added"); } } }
public Task <HostCompilationStartAnalysisScope> GetCompilationAnalysisScopeAsync( HostSessionStartAnalysisScope sessionScope, AnalyzerExecutor analyzerExecutor) { lock (_gate) { _lazyCompilationScopeCache = _lazyCompilationScopeCache ?? new ConditionalWeakTable <Compilation, Dictionary <AnalyzerOptions, Task <HostCompilationStartAnalysisScope> > >(); var compilationActionsMap = _lazyCompilationScopeCache.GetOrCreateValue(analyzerExecutor.Compilation); Task <HostCompilationStartAnalysisScope> task; if (!compilationActionsMap.TryGetValue(analyzerExecutor.AnalyzerOptions, out task)) { task = Task.Run(() => { var compilationAnalysisScope = new HostCompilationStartAnalysisScope(sessionScope); analyzerExecutor.ExecuteCompilationStartActions(sessionScope.CompilationStartActions, compilationAnalysisScope); return(compilationAnalysisScope); }, analyzerExecutor.CancellationToken); compilationActionsMap.Add(analyzerExecutor.AnalyzerOptions, task); } return(task); } }
public static IMethodSymbol GetMethodSymbol(Compilation compilation, MethodInfo method) { var methodMap = methodMapMap.GetOrCreateValue(compilation); if (!methodMap.TryGetValue(method, out var methodSymbol)) { methodSymbol = CreateMethodSymbol(); #if DEBUG if (methodSymbol != null) #endif methodMap.Add(method, methodSymbol); } return(methodSymbol); IMethodSymbol CreateMethodSymbol() { var typeSymbol = GetTypeSymbol(compilation, method.DeclaringType); var parameterTypes = GetTypeSymbols(compilation, method.GetParameters().Select(p => p.ParameterType).ToArray()); var namedMembers = typeSymbol.GetMembers(method.Name); foreach (var m in namedMembers) { if (m is IMethodSymbol ms) { if (Matches(ms.Parameters, parameterTypes)) { return(ms); } } } return(null); } }
/// <summary> /// Atomically gets or sets an attached value if it's found. /// </summary> public static AttachmentResult <T> GetOrSetAttached <T>(this object host, Func <T> factory, string key = null) { if (host == null) { throw new ArgumentNullException(nameof(host)); } if (factory == null) { throw new ArgumentNullException(nameof(factory)); } key = key ?? typeof(T).AssemblyQualifiedName; var dict = _attachmentTable.GetOrCreateValue(host); var found = true; var value = dict.GetOrAdd(key, _ => { found = false; return(factory()); }); var castValue = (T)value; return(new AttachmentResult <T>(found, castValue)); }
private static void SerializeExceptionsForDump(Exception currentException, IntPtr exceptionCCWPtr, LowLevelList <byte[]> serializedExceptions) { const UInt32 NoInnerExceptionValue = 0xFFFFFFFF; // Approximate upper size limit for the serialized exceptions (but we'll always serialize currentException) // If we hit the limit, because we serialize in arbitrary order, there may be missing InnerExceptions or nested exceptions. const int MaxBufferSize = 20000; int nExceptions; RuntimeImports.RhGetExceptionsForCurrentThread(null, out nExceptions); Exception[] curThreadExceptions = new Exception[nExceptions]; RuntimeImports.RhGetExceptionsForCurrentThread(curThreadExceptions, out nExceptions); LowLevelList <Exception> exceptions = new LowLevelList <Exception>(curThreadExceptions); LowLevelList <Exception> nonThrownInnerExceptions = new LowLevelList <Exception>(); uint currentThreadId = Interop.mincore.GetCurrentThreadId(); // Reset nesting levels for exceptions on this thread that might not be currently in flight foreach (ExceptionData exceptionData in s_exceptionDataTable.GetValues()) { if (exceptionData.ExceptionMetadata.ThreadId == currentThreadId) { exceptionData.ExceptionMetadata.NestingLevel = -1; } } // Find all inner exceptions, even if they're not currently being handled for (int i = 0; i < exceptions.Count; i++) { if (exceptions[i].InnerException != null && !exceptions.Contains(exceptions[i].InnerException)) { exceptions.Add(exceptions[i].InnerException); nonThrownInnerExceptions.Add(exceptions[i].InnerException); } } int currentNestingLevel = curThreadExceptions.Length - 1; // Populate exception data for all exceptions interesting to this thread. // Whether or not there was previously data for that object, it might have changed. for (int i = 0; i < exceptions.Count; i++) { ExceptionData exceptionData = s_exceptionDataTable.GetOrCreateValue(exceptions[i]); exceptionData.ExceptionMetadata.ExceptionId = (UInt32)System.Threading.Interlocked.Increment(ref s_currentExceptionId); if (exceptionData.ExceptionMetadata.ExceptionId == NoInnerExceptionValue) { exceptionData.ExceptionMetadata.ExceptionId = (UInt32)System.Threading.Interlocked.Increment(ref s_currentExceptionId); } exceptionData.ExceptionMetadata.ThreadId = currentThreadId; // Only include nesting information for exceptions that were thrown on this thread if (!nonThrownInnerExceptions.Contains(exceptions[i])) { exceptionData.ExceptionMetadata.NestingLevel = currentNestingLevel; currentNestingLevel--; } else { exceptionData.ExceptionMetadata.NestingLevel = -1; } // Only match the CCW pointer up to the current exception if (Object.ReferenceEquals(exceptions[i], currentException)) { exceptionData.ExceptionMetadata.ExceptionCCWPtr = exceptionCCWPtr; } byte[] serializedEx = exceptions[i].SerializeForDump(); exceptionData.SerializedExceptionData = serializedEx; } // Populate inner exception ids now that we have all of them in the table for (int i = 0; i < exceptions.Count; i++) { ExceptionData exceptionData; if (!s_exceptionDataTable.TryGetValue(exceptions[i], out exceptionData)) { // This shouldn't happen, but we can't meaningfully throw here continue; } if (exceptions[i].InnerException != null) { ExceptionData innerExceptionData; if (s_exceptionDataTable.TryGetValue(exceptions[i].InnerException, out innerExceptionData)) { exceptionData.ExceptionMetadata.InnerExceptionId = innerExceptionData.ExceptionMetadata.ExceptionId; } } else { exceptionData.ExceptionMetadata.InnerExceptionId = NoInnerExceptionValue; } } int totalSerializedExceptionSize = 0; // Make sure we include the current exception, regardless of buffer size ExceptionData currentExceptionData = null; if (s_exceptionDataTable.TryGetValue(currentException, out currentExceptionData)) { byte[] serializedExceptionData = currentExceptionData.Serialize(); serializedExceptions.Add(serializedExceptionData); totalSerializedExceptionSize = serializedExceptionData.Length; } checked { foreach (ExceptionData exceptionData in s_exceptionDataTable.GetValues()) { // Already serialized currentException if (currentExceptionData != null && exceptionData.ExceptionMetadata.ExceptionId == currentExceptionData.ExceptionMetadata.ExceptionId) { continue; } byte[] serializedExceptionData = exceptionData.Serialize(); if (totalSerializedExceptionSize + serializedExceptionData.Length >= MaxBufferSize) { break; } serializedExceptions.Add(serializedExceptionData); totalSerializedExceptionSize += serializedExceptionData.Length; } } }
// EventRegistrationToken CollectionChanged.add(NotifyCollectionChangedEventHandler value) internal EventRegistrationToken add_CollectionChanged(NotifyCollectionChangedEventHandler value) { INotifyCollectionChanged _this = Unsafe.As <INotifyCollectionChanged>(this); EventRegistrationTokenTable <NotifyCollectionChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this); EventRegistrationToken token = table.AddEventHandler(value); _this.CollectionChanged += value; return(token); }
public static void SetValue <T>(object root, string key, T value) { var dictionary = _table.GetOrCreateValue(root); dictionary.AddOrUpdate(key, value, (x, y) => value); }
public IdBindingProperty CreateBindingId( OriginalStringBindingProperty originalString = null, ParsedExpressionBindingProperty expression = null, DataContextStack dataContext = null, ResolvedBinding resolvedBinding = null, LocationInfoBindingProperty locationInfo = null) { var sb = new StringBuilder(); if (resolvedBinding?.TreeRoot != null && dataContext != null) { var bindingIndex = bindingCounts.GetOrCreateValue(resolvedBinding.TreeRoot).AddOrUpdate(dataContext, 0, (_, i) => i + 1); sb.Append(bindingIndex); sb.Append(" || "); } // don't append expression when original string is present, so it does not have to be always exactly same if (originalString != null) { sb.Append(originalString.Code); } else { sb.Append(expression.Expression.ToString()); } sb.Append(" || "); while (dataContext != null) { sb.Append(dataContext.DataContextType.FullName); sb.Append('('); foreach (var ns in dataContext.NamespaceImports) { sb.Append(ns.Alias); sb.Append('='); sb.Append(ns.Namespace); } sb.Append(';'); foreach (var ext in dataContext.ExtensionParameters) { sb.Append(ext.Identifier); if (ext.Inherit) { sb.Append('*'); } sb.Append(':'); sb.Append(ext.ParameterType.FullName); sb.Append(':'); sb.Append(ext.GetType().FullName); } sb.Append(") -- "); dataContext = dataContext.Parent; } sb.Append(" || "); sb.Append(locationInfo?.RelatedProperty?.FullName); using (var sha = System.Security.Cryptography.SHA256.Create()) { var hash = sha.ComputeHash(Encoding.Unicode.GetBytes(sb.ToString())); // use just 12 bytes = 96 bits return(new IdBindingProperty(Convert.ToBase64String(hash, 0, 12))); } }
public static void Set <T, TValue>(T target, string propertyName, TValue value) { var properties = _store.GetOrCreateValue(target); properties[propertyName] = value; }
public static NavigableContentType GetContentType(IPublishedContentType contentType) { return(TypesMap.GetOrCreateValue(contentType).EnsureInitialized(contentType)); }
internal static MTexture2D Meta(this Texture2D @this) { return(Texture2DMetaTable.GetOrCreateValue(@this)); }
public void SetAttribute(string attributeName, object attributeValue) { var dic = Attributes.GetOrCreateValue(this); dic[attributeName] = attributeValue; }
public static T Get <T>(this object obj) where T : class { var dict = table.GetOrCreateValue(obj); return(dict[typeof(T)] as T); }
public static Dictionary <string, Type> GetVars(object stack, bool ignoreCase) { return(ignoreCase ? VarsIgnoreCase.GetOrCreateValue(stack) : Vars.GetOrCreateValue(stack)); }
public DefaultDateTimeSerializationFormatProvider(ITypeSerializer serializer) { _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); _cache = CacheSet.GetOrCreateValue(serializer); }
public static dynamic Props(this object key) { return(props.GetOrCreateValue(key)); }
private bool _disposedValue = false; // To detect redundant calls internal RepositoryLocker(RepositoryReader reader) { _reader = reader; _lock = _locks.GetOrCreateValue(reader); _reentrant = LockDatabase(); }
public static T GetOrAddExtension <T>(this object obj, string key, Func <T> factory) { var extendedData = _extendedDataTable.GetOrCreateValue(obj); return((T)extendedData.GetOrAdd(key, k => factory())); }