Beispiel #1
0
		static SearchBoxProperties()
		{
			_suggestionRequestedEventHandlers = new ConditionalWeakTable<SearchBox, TypedEventHandler<SearchBox, SearchBoxSuggestionsRequestedEventArgs>>();
			_resultSuggestionChosenEventHandlers = new ConditionalWeakTable<SearchBox, TypedEventHandler<SearchBox, SearchBoxResultSuggestionChosenEventArgs>>();
			_dataContextChangedEventHandlers = new ConditionalWeakTable<SearchBox, TypedEventHandler<FrameworkElement, DataContextChangedEventArgs>>();
			_querySubmittedCommandEventHandlers = new ConditionalWeakTable<SearchBox, TypedEventHandler<SearchBox, SearchBoxQuerySubmittedEventArgs>>();
		}
Beispiel #2
0
 /// <inheritdoc/>
 public void Clear()
 {
     lock (objectGuids)
     {
         objectGuids = new ConditionalWeakTable<object, object>();
     }
 }
        protected async Task<bool> SaveAsync(
            Document document,
            ConditionalWeakTable<BranchId, ConditionalWeakTable<DocumentId, AbstractSyntaxTreeInfo>> cache,
            string persistenceName,
            string serializationFormat,
            CancellationToken cancellationToken)
        {
            var workspace = document.Project.Solution.Workspace;
            var infoTable = GetInfoTable(document.Project.Solution.BranchId, workspace, cache);

            // if it is forked document
            if (await document.IsForkedDocumentWithSyntaxChangesAsync(cancellationToken).ConfigureAwait(false))
            {
                infoTable.Remove(document.Id);
                infoTable.GetValue(document.Id, _ => this);
                return false;
            }

            // okay, cache this info if it is from opened document or persistence failed.
            var persisted = await SaveAsync(document, persistenceName, serializationFormat, this, cancellationToken).ConfigureAwait(false);
            if (!persisted || document.IsOpen())
            {
                var primaryInfoTable = GetInfoTable(workspace.PrimaryBranchId, workspace, cache);
                primaryInfoTable.Remove(document.Id);
                primaryInfoTable.GetValue(document.Id, _ => this);
            }

            return persisted;
        }
Beispiel #4
0
        private static async Task<SyntaxTreeIndex> GetIndexAsync(
            Document document,
            ConditionalWeakTable<Document, SyntaxTreeIndex> cache,
            Func<Document, CancellationToken, Task<SyntaxTreeIndex>> generator,
            CancellationToken cancellationToken)
        {
            if (cache.TryGetValue(document, out var info))
            {
                return info;
            }

            info = await generator(document, cancellationToken).ConfigureAwait(false);
            if (info != null)
            {
                return cache.GetValue(document, _ => info);
            }

            // alright, we don't have cached information, re-calculate them here.
            var data = await CreateInfoAsync(document, cancellationToken).ConfigureAwait(false);

            // okay, persist this info
            await data.SaveAsync(document, cancellationToken).ConfigureAwait(false);

            return cache.GetValue(document, _ => data);
        }
        public Task<XmlNodeSyntax> GetSyntaxTree(ITextSnapshot textSnapshot)
        {
            var textBuffer = textSnapshot.TextBuffer;

            lock (textBuffer)
            {
                ConditionalWeakTable<ITextSnapshot, Task<XmlNodeSyntax>> textSnapshotToSyntaxRootMap;
                Task<XmlNodeSyntax> syntaxRootTask;

                if (!textBuffer.Properties.TryGetProperty(typeof(ParserService), out textSnapshotToSyntaxRootMap))
                {
                    textSnapshotToSyntaxRootMap = new ConditionalWeakTable<ITextSnapshot, Task<XmlNodeSyntax>>();
                    textBuffer.Properties.AddProperty(typeof(ParserService), textSnapshotToSyntaxRootMap);
                }
                else if (textSnapshotToSyntaxRootMap.TryGetValue(textSnapshot, out syntaxRootTask))
                {
                    return syntaxRootTask;
                }

                syntaxRootTask = Task.Run(() => Parse(textSnapshot));
                textSnapshotToSyntaxRootMap.Add(textSnapshot, syntaxRootTask);

                return syntaxRootTask;
            }
        }
        public void GetValue()
        {
            var cwt = new ConditionalWeakTable<object, object>();

            try
            {
                cwt.GetValue(null, k => null);
                Assert.Fail("#0");
            }
            catch (ArgumentNullException) { }

            try
            {
                cwt.GetValue(20, null);
                Assert.Fail("#1");
            }
            catch (ArgumentNullException) { }


            object key = "foo";
            object val = cwt.GetValue(key, k => new Link(k));
            Assert.IsTrue(val != null, "#2");
            Assert.AreEqual(typeof(Link), val.GetType(), "#3");

            Assert.AreEqual(val, cwt.GetValue(key, k => new object()), "#4");
        }
        public static void AddMany_ThenRemoveAll(int numObjects)
        {
            object[] keys = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray();
            object[] values = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray();
            var cwt = new ConditionalWeakTable<object, object>();

            for (int i = 0; i < numObjects; i++)
            {
                cwt.Add(keys[i], values[i]);
            }

            for (int i = 0; i < numObjects; i++)
            {
                Assert.Same(values[i], cwt.GetValue(keys[i], _ => new object()));
            }

            for (int i = 0; i < numObjects; i++)
            {
                Assert.True(cwt.Remove(keys[i]));
                Assert.False(cwt.Remove(keys[i]));
            }

            for (int i = 0; i < numObjects; i++)
            {
                object ignored;
                Assert.False(cwt.TryGetValue(keys[i], out ignored));
            }
        }
Beispiel #8
0
        internal void OnNewAnalyzer(PythonAnalyzer analyzer) {
            if (analyzer == null) {
                throw new ArgumentNullException("analyzer");
            }

            _tags.Clear();
            _filters.Clear();
            foreach (var entry in _hookedEntries) {
                entry.OnNewParseTree -= OnNewParseTree;
            }
            _hookedEntries.Clear();
            _templateAnalysis.Clear();
            _templateFiles.Clear();
            _contextTable = new ConditionalWeakTable<Node, ContextMarker>();
            _decoratorTable = new ConditionalWeakTable<Node, DeferredDecorator>();

            foreach (var keyValue in _knownTags) {
                _tags[keyValue.Key] = new TagInfo(keyValue.Value, null);
            }
            foreach (var keyValue in _knownFilters) {
                _filters[keyValue.Key] = new TagInfo(keyValue.Value, null);
            }

            HookAnalysis(analyzer);
            _analyzer = analyzer;
        }
 /// <summary>
 /// Executes an action.
 /// </summary>
 public ObservableCommand(Func<object, bool> canExecuteFunc = null, bool enabled = true)
 {
     this.enabled = enabled;
     this.canExecuteFunc = canExecuteFunc;
     this.proxies = new List<WeakReference<ObservableCommandProxy>>();
     this.proxyHandlers = new ConditionalWeakTable<ObservableCommandProxy, EventHandler>();
 }
        public void Should_release_value_when_there_are_no_more_references()
        {
            var table = new ConditionalWeakTable<TypeWithStrongReferenceThroughTable, TypeWithWeakReference>();

            var strong = new TypeWithStrongReferenceThroughTable();
            var weak = new TypeWithWeakReference()
                {
                    WeakReference = new WeakReference(strong)
                };

            table.Add(strong, weak);

            GC.Collect();

            TypeWithWeakReference result = null;
            Assert.That(table.TryGetValue(strong, out result), Is.True);
            Assert.That(result, Is.SameAs(weak));

            var weakHandleToStrong = new WeakReference(strong);

            strong = null;

            GC.Collect();

            Assert.That(weakHandleToStrong.IsAlive, Is.False);
        }
Beispiel #11
0
        private static void WeakKey()
        {
            var people = new[]
            {
                new Person {Id = 1, Name = "Jurian Naul" },
                new Person {Id = 2, Name = "Thomas Bent" },
                new Person {Id = 3, Name = "Ellen Carson" },
                new Person {Id = 4, Name = "Katrina Lauran" },
                new Person {Id = 5, Name = "Monica Ausbach" },
            };

            var locations = new ConditionalWeakTable<Person, string>();

            locations.Add(people[0], "Shinon");
            locations.Add(people[1], "Lance");
            locations.Add(people[2], "Pidona");
            locations.Add(people[3], "Loanne");
            locations.Add(people[4], "Loanne");

            foreach (var p in people)
            {
                string location;
                if (locations.TryGetValue(p, out location))
                    Console.WriteLine(p.Name + " at " + location);
            }
        }
        /// <summary>Static constructor.</summary>
        static QueryFutureManager()
        {
#if EF5 || EF6
            CacheWeakFutureBatch = new ConditionalWeakTable<ObjectContext, QueryFutureBatch>();
#elif EFCORE
            CacheWeakFutureBatch = new ConditionalWeakTable<DbContext, QueryFutureBatch>();
#endif
        }
Beispiel #13
0
 public AnalysisState(ImmutableArray<DiagnosticAnalyzer> analyzers)
 {
     _gate = new object();
     _analyzerStateMap = CreateAnalyzerStateMap(analyzers);
     _pendingSourceEvents = new Dictionary<SyntaxTree, HashSet<CompilationEvent>>();
     _pendingNonSourceEvents = new HashSet<CompilationEvent>();
     _lazyAnalyzerActionCountsMap = null;
     _semanticModelsMap = new ConditionalWeakTable<SyntaxTree, SemanticModel>();
     _compilationEventsPool = new ObjectPool<HashSet<CompilationEvent>>(() => new HashSet<CompilationEvent>());
 }
Beispiel #14
0
        public AnalyzerManager(ImmutableArray<AnalyzerReference> hostAnalyzerReferences)
        {
            _hostAnalyzerReferencesMap = hostAnalyzerReferences.IsDefault ? ImmutableDictionary<string, AnalyzerReference>.Empty : CreateAnalyzerReferencesMap(hostAnalyzerReferences);
            _hostDiagnosticAnalyzersPerReferenceMap = CreateDiagnosticAnalyzersPerReferenceMap(_hostAnalyzerReferencesMap);

            _hostDiagnosticAnalyzersPerLanguageMap = new ConcurrentDictionary<string, ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>>>(concurrencyLevel: 2, capacity: 2);
            _descriptorCache = new ConditionalWeakTable<DiagnosticAnalyzer, IReadOnlyList<DiagnosticDescriptor>>();

            DiagnosticAnalyzerLogger.LogWorkspaceAnalyzers(hostAnalyzerReferences);
        }
        private bool TryGetInitialVersions(ConditionalWeakTable<ProjectId, Versions> initialVersionMap, Project project, string keyName, out Versions versions)
        {
            // if we already loaded this, return it.
            if (initialVersionMap.TryGetValue(project.Id, out versions))
            {
                return true;
            }

            // otherwise, load it
            return TryLoadInitialVersions(initialVersionMap, project, keyName, out versions);
        }
Beispiel #16
0
 public AnalysisState(ImmutableArray<DiagnosticAnalyzer> analyzers)
 {
     _gate = new SemaphoreSlim(initialCount: 1);
     _analyzerStateMap = CreateAnalyzerStateMap(analyzers, out _analyzerStates);
     _pendingSourceEvents = new Dictionary<SyntaxTree, HashSet<CompilationEvent>>();
     _pendingNonSourceEvents = new HashSet<CompilationEvent>();
     _lazyAnalyzerActionCountsMap = null;
     _semanticModelsMap = new ConditionalWeakTable<SyntaxTree, SemanticModel>();
     _compilationEventsPool = new ObjectPool<HashSet<CompilationEvent>>(() => new HashSet<CompilationEvent>());
     _pooledEventsWithAnyActionsSet = new HashSet<CompilationEvent>();
     _compilationEndAnalyzed = false;
 }
Beispiel #17
0
 private static void InitializeEnableXamlSourceInfo(string value)
 {
     // Initialize source info support. Source info is disabled if value
     // is empty, 0 or false (case insensitive). Otherwise true.
     value = (value ?? string.Empty).Trim().ToLowerInvariant();
     if (value == string.Empty || value == "0" || value == "false" || !InitializeXamlObjectEventArgs())
     {
         s_sourceInfoTable = null;
     }
     else
     {
         s_sourceInfoTable = new ConditionalWeakTable<object, XamlSourceInfo>();
     }
 }
        public static void InvalidArgs_Throws()
        {
            var cwt = new ConditionalWeakTable<object, object>();

            object ignored;
            Assert.Throws<ArgumentNullException>("key", () => cwt.Add(null, new object())); // null key
            Assert.Throws<ArgumentNullException>("key", () => cwt.TryGetValue(null, out ignored)); // null key
            Assert.Throws<ArgumentNullException>("key", () => cwt.Remove(null)); // null key
            Assert.Throws<ArgumentNullException>("createValueCallback", () => cwt.GetValue(new object(), null)); // null delegate

            object key = new object();
            cwt.Add(key, key);
            Assert.Throws<ArgumentException>(null, () => cwt.Add(key, key)); // duplicate key
        }
Beispiel #19
0
        private ConditionalWeakTable<Compilation, Task<HostCompilationStartAnalysisScope>> GetOrCreateCompilationActionsCache(AnalyzerAndOptions analyzerAndOptions)
        {
            lock (_compilationScopeMap)
            {
                ConditionalWeakTable<Compilation, Task<HostCompilationStartAnalysisScope>> value;
                if (_compilationScopeMap.TryGetValue(analyzerAndOptions, out value))
                {
                    return value;
                }

                value = new ConditionalWeakTable<Compilation, Task<HostCompilationStartAnalysisScope>>();
                _compilationScopeMap.Add(analyzerAndOptions, value);
                return value;
            }
        }
Beispiel #20
0
 public AnalysisState(ImmutableArray<DiagnosticAnalyzer> analyzers, CompilationData compilationData)
 {
     _gate = new object();
     _analyzerStateMap = CreateAnalyzerStateMap(analyzers, out _analyzerStates);
     _compilationData = compilationData;
     _pendingSourceEvents = new Dictionary<SyntaxTree, HashSet<CompilationEvent>>();
     _pendingNonSourceEvents = new HashSet<CompilationEvent>();
     _lazyAnalyzerActionCountsMap = null;
     _semanticModelsMap = new ConditionalWeakTable<SyntaxTree, SemanticModel>();
     _treesWithGeneratedSourceEvents = new HashSet<SyntaxTree>();
     _partialSymbolsWithGeneratedSourceEvents = new HashSet<ISymbol>();
     _compilationStartGenerated = false;
     _compilationEndGenerated = false;
     _compilationEventsPool = new ObjectPool<HashSet<CompilationEvent>>(() => new HashSet<CompilationEvent>());
     _pooledEventsWithAnyActionsSet = new HashSet<CompilationEvent>();
 }
            public Task<HostCompilationStartAnalysisScope> GetCompilationAnalysisScopeAsync(
                HostSessionStartAnalysisScope sessionScope,
                AnalyzerExecutor analyzerExecutor)
            {
                Func<Compilation, Task<HostCompilationStartAnalysisScope>> getTask = comp =>
                {
                    return Task.Run(() =>
                    {
                        var compilationAnalysisScope = new HostCompilationStartAnalysisScope(sessionScope);
                        analyzerExecutor.ExecuteCompilationStartActions(sessionScope.CompilationStartActions, compilationAnalysisScope);
                        return compilationAnalysisScope;
                    }, analyzerExecutor.CancellationToken);
                };

                var callback = new ConditionalWeakTable<Compilation, Task<HostCompilationStartAnalysisScope>>.CreateValueCallback(getTask);
                var compilationActionsCache = GetOrCreateCompilationActionsCache(analyzerExecutor.AnalyzerOptions);
                return compilationActionsCache.GetValue(analyzerExecutor.Compilation, callback);
            }
Beispiel #22
0
   /* 
   * Ensure that a key that has no managed references to it gets automatically removed from the 
   * dictionary after GC happens. Also make sure the value gets gc’d as well. 
   */
    public static void TestKeyWithNoReferences_Pass1(int length)
    {
        tbl = new ConditionalWeakTable<string, string>();

        weakRefKeyArr = new WeakReference[length];
        weakRefValArr = new WeakReference[length];

        for (int i = 0; i < length; i++)
        {
            String key = "KeyTestString" + i.ToString();
            String value = "ValueTestString" + i.ToString();
            tbl.Add(key, value);
            
            // create a weak reference for the key
            weakRefKeyArr[i] = new WeakReference(key, true);
            weakRefValArr[i] = new WeakReference(value, true);
        }
    }
        private Task<HostCompilationStartAnalysisScope> GetCompilationAnalysisScopeCoreAsync(
            AnalyzerAndOptions analyzerAndOptions,
            HostSessionStartAnalysisScope sessionScope,
            AnalyzerExecutor analyzerExecutor)
        {
            Func<Compilation, Task<HostCompilationStartAnalysisScope>> getTask = comp =>
            {
                return Task.Run(() =>
                {
                    var compilationAnalysisScope = new HostCompilationStartAnalysisScope(sessionScope);
                    analyzerExecutor.ExecuteCompilationStartActions(sessionScope.CompilationStartActions, compilationAnalysisScope);
                    return compilationAnalysisScope;
                }, analyzerExecutor.CancellationToken);
            };

            var callback = new ConditionalWeakTable<Compilation, Task<HostCompilationStartAnalysisScope>>.CreateValueCallback(getTask);
            var compilationActionsMap = _compilationScopeMap.GetOrAdd(analyzerAndOptions, new ConditionalWeakTable<Compilation, Task<HostCompilationStartAnalysisScope>>());
            return compilationActionsMap.GetValue(analyzerExecutor.Compilation, callback);
        }
        protected static async Task<AbstractSyntaxTreeInfo> LoadAsync(
            Document document,
            Func<ObjectReader, VersionStamp, AbstractSyntaxTreeInfo> reader,
            ConditionalWeakTable<BranchId, ConditionalWeakTable<DocumentId, AbstractSyntaxTreeInfo>> cache,
            string persistenceName,
            string serializationFormat,
            CancellationToken cancellationToken)
        {
            var infoTable = cache.GetValue(document.Project.Solution.BranchId, _ => new ConditionalWeakTable<DocumentId, AbstractSyntaxTreeInfo>());
            var version = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false);

            // first look to see if we already have the info in the cache
            AbstractSyntaxTreeInfo info;
            if (infoTable.TryGetValue(document.Id, out info) && info.Version == version)
            {
                return info;
            }

            // cache is invalid. remove it
            infoTable.Remove(document.Id);

            // check primary cache to see whether we have valid info there
            var primaryInfoTable = cache.GetValue(document.Project.Solution.Workspace.PrimaryBranchId, _ => new ConditionalWeakTable<DocumentId, AbstractSyntaxTreeInfo>());
            if (primaryInfoTable.TryGetValue(document.Id, out info) && info.Version == version)
            {
                return info;
            }

            // check whether we can get it from persistence service
            info = await LoadAsync(document, persistenceName, serializationFormat, reader, cancellationToken).ConfigureAwait(false);
            if (info != null)
            {
                // save it in the cache. persisted info is always from primary branch. no reason to save it to the branched document cache.
                primaryInfoTable.Remove(document.Id);
                primaryInfoTable.GetValue(document.Id, _ => info);
                return info;
            }

            // well, we don't have this information.
            return null;
        }
Beispiel #25
0
    // this test ensures that while manipulating keys (through add/remove/lookup
    // in the dictionary the overriden GetHashCode(), Equals(), and ==operator do not get invoked.
    // Earlier implementation was using these functions virtually so overriding them would result in 
    // the overridden functions being invoked. But later on Ati changed implementation to use 
    // Runtime.GetHashCode and Object.ReferenceEquals so this test makes sure that overridden functions never get invoked.
    public static void TestOverrides()
    {
        string[] stringArr = new string[50];
        for (int i = 0; i < 50; i++)
        {
            stringArr[i] = "SomeTestString" + i.ToString();
        }

        ConditionalWeakTable<string, string> tbl = new ConditionalWeakTable<string, string>();

        string str;

        for (int i = 0; i < stringArr.Length; i++)
        {
            tbl.Add(stringArr[i], stringArr[i]);

            tbl.TryGetValue(stringArr[i], out str);

            tbl.Remove(stringArr[i]);
        }
    }
    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));
    }
Beispiel #27
0
        public CodeFixService(
            IDiagnosticAnalyzerService service,
            [ImportMany]IEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> fixers,
            [ImportMany]IEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>> suppressionProviders)
        {
            _diagnosticService = service;

            var fixersPerLanguageMap = fixers.ToPerLanguageMapWithMultipleLanguages();
            var suppressionProvidersPerLanguageMap = suppressionProviders.ToPerLanguageMapWithMultipleLanguages();

            _workspaceFixersMap = GetFixerPerLanguageMap(fixersPerLanguageMap);
            _suppressionProvidersMap = GetSupressionProvidersPerLanguageMap(suppressionProvidersPerLanguageMap);

            // REVIEW: currently, fixer's priority is statically defined by the fixer itself. might considering making it more dynamic or configurable.
            _fixerPriorityMap = GetFixerPriorityPerLanguageMap(fixersPerLanguageMap);

            // Per-project fixers
            _projectFixersMap = new ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<string, List<CodeFixProvider>>>();
            _analyzerReferenceToFixersMap = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>();
            _createProjectCodeFixProvider = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>.CreateValueCallback(r => new ProjectCodeFixProvider(r));
            _fixAllProviderMap = ImmutableDictionary<CodeFixProvider, FixAllProviderInfo>.Empty;
        }
	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) {}
	}
        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}");
            }
        }
Beispiel #30
0
        private void SubscribeNotifyChangedEvent(object value, EventChangeType eventChangeType, bool isCollectionItem)
        {
            if (value == null)
            {
                return;
            }

            lock (_lockObject)
            {
                ConditionalWeakTable <object, IWeakEventListener> eventsTable;
                List <IWeakEventListener> eventsList;

                switch (eventChangeType)
                {
                case EventChangeType.Property:
                    if (_weakPropertyChangedListenersTable == null)
                    {
                        _weakPropertyChangedListenersTable = new ConditionalWeakTable <object, IWeakEventListener>();
                    }

                    if (_weakPropertyChangedListeners == null)
                    {
                        _weakPropertyChangedListeners = new List <IWeakEventListener>();
                    }

                    eventsTable = _weakPropertyChangedListenersTable;
                    eventsList  = _weakPropertyChangedListeners;
                    break;

                case EventChangeType.Collection:
                    if (_weakCollectionChangedListenersTable == null)
                    {
                        _weakCollectionChangedListenersTable = new ConditionalWeakTable <object, IWeakEventListener>();
                    }

                    if (_weakCollectionChangedListeners == null)
                    {
                        _weakCollectionChangedListeners = new List <IWeakEventListener>();
                    }

                    if (_collectionItems == null)
                    {
                        _collectionItems = new ConditionalWeakTable <object, List <WeakReference> >();
                    }

                    eventsTable = _weakCollectionChangedListenersTable;
                    eventsList  = _weakCollectionChangedListeners;
                    break;

                default:
                    throw new ArgumentOutOfRangeException("eventChangeType");
                }

                IWeakEventListener oldSubscription;
                if (eventsTable.TryGetValue(value, out oldSubscription))
                {
                    oldSubscription.Detach();

                    eventsList.Remove(oldSubscription);
                    eventsTable.Remove(value);
                }

                IWeakEventListener weakListener;
                switch (eventChangeType)
                {
                case EventChangeType.Property:
                    if (isCollectionItem)
                    {
                        weakListener = this.SubscribeToWeakPropertyChangedEvent(value, OnObjectCollectionItemPropertyChanged);
                    }
                    else
                    {
                        weakListener = this.SubscribeToWeakPropertyChangedEvent(value, OnObjectPropertyChanged);
                    }
                    break;

                case EventChangeType.Collection:
                    weakListener = this.SubscribeToWeakCollectionChangedEvent(value, OnObjectCollectionChanged);

                    var collection = value as ICollection;
                    if (collection != null)
                    {
                        var collectionItems = new List <WeakReference>();
                        foreach (var item in collection)
                        {
                            collectionItems.Add(new WeakReference(item));
                        }

                        _collectionItems.Add(value, collectionItems);
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException("eventChangeType");
                }

                eventsTable.Add(value, weakListener);
                eventsList.Add(weakListener);
            }
        }
 protected override SchedulerWrapper Clone(IScheduler scheduler, ConditionalWeakTable <IScheduler, IScheduler> cache)
 {
     return(new DisableOptimizationsScheduler(scheduler, _optimizationInterfaces, cache));
 }
 public static T GetOrCreate <T>(object value, ConditionalWeakTable <object, object> .CreateValueCallback checksumCreator) where T : IChecksummedObject
 {
     // same key should always return same checksum
     return((T)s_cache.GetValue(value, checksumCreator));
 }
 public static IReadOnlyList <T> GetOrCreate <T>(IReadOnlyList <T> unorderedList, ConditionalWeakTable <object, object> .CreateValueCallback orderedListGetter)
 {
     return((IReadOnlyList <T>)s_cache.GetValue(unorderedList, orderedListGetter));
 }
Beispiel #34
0
 /// <inheritdoc />
 protected ReferenceCacheBase(ConditionalWeakTable <TKey, TValue> cache)
 {
     _cache    = cache;
     _callback = Create;
 }
Beispiel #35
0
 internal SessionStateKeeper()
 {
     _stateMap = new ConditionalWeakTable <Runspace, SessionStateInternal>();
 }
 static HttpClientHander()
 {
     _httpClientsPool = new ConditionalWeakTable <Uri, HttpClientHander>();
     _uris            = new HashSet <Uri>();
     SetupGlobalPoolFinalizer();
 }
Beispiel #37
0
        internal ReadyToRunCodegenCompilation(
            DependencyAnalyzerBase <NodeFactory> dependencyGraph,
            NodeFactory nodeFactory,
            IEnumerable <ICompilationRootProvider> roots,
            ILProvider ilProvider,
            Logger logger,
            DevirtualizationManager devirtualizationManager,
            IEnumerable <string> inputFiles,
            string compositeRootPath,
            InstructionSetSupport instructionSetSupport,
            bool resilient,
            bool generateMapFile,
            bool generateMapCsvFile,
            bool generatePdbFile,
            Func <MethodDesc, string> printReproInstructions,
            string pdbPath,
            bool generatePerfMapFile,
            string perfMapPath,
            int parallelism,
            ProfileDataManager profileData,
            ReadyToRunMethodLayoutAlgorithm methodLayoutAlgorithm,
            ReadyToRunFileLayoutAlgorithm fileLayoutAlgorithm,
            int customPESectionAlignment,
            bool verifyTypeAndFieldLayout)
            : base(
                dependencyGraph,
                nodeFactory,
                roots,
                ilProvider,
                devirtualizationManager,
                modulesBeingInstrumented: nodeFactory.CompilationModuleGroup.CompilationModuleSet,
                logger,
                instructionSetSupport)
        {
            _resilient                = resilient;
            _parallelism              = parallelism;
            _generateMapFile          = generateMapFile;
            _generateMapCsvFile       = generateMapCsvFile;
            _generatePdbFile          = generatePdbFile;
            _pdbPath                  = pdbPath;
            _generatePerfMapFile      = generatePerfMapFile;
            _perfMapPath              = perfMapPath;
            _customPESectionAlignment = customPESectionAlignment;
            SymbolNodeFactory         = new ReadyToRunSymbolNodeFactory(nodeFactory, verifyTypeAndFieldLayout);
            _corInfoImpls             = new ConditionalWeakTable <Thread, CorInfoImpl>();
            _inputFiles               = inputFiles;
            _compositeRootPath        = compositeRootPath;
            _printReproInstructions   = printReproInstructions;
            CompilationModuleGroup    = (ReadyToRunCompilationModuleGroupBase)nodeFactory.CompilationModuleGroup;

            // Generate baseline support specification for InstructionSetSupport. This will prevent usage of the generated
            // code if the runtime environment doesn't support the specified instruction set
            string instructionSetSupportString = ReadyToRunInstructionSetSupportSignature.ToInstructionSetSupportString(instructionSetSupport);
            ReadyToRunInstructionSetSupportSignature instructionSetSupportSig = new ReadyToRunInstructionSetSupportSignature(instructionSetSupportString);

            _dependencyGraph.AddRoot(new Import(NodeFactory.EagerImports, instructionSetSupportSig), "Baseline instruction set support");

            _profileData = profileData;

            _fileLayoutOptimizer = new ReadyToRunFileLayoutOptimizer(methodLayoutAlgorithm, fileLayoutAlgorithm, profileData, _nodeFactory);
        }
 public DisableOptimizationsScheduler(IScheduler scheduler, Type[] optimizationInterfaces, ConditionalWeakTable <IScheduler, IScheduler> cache)
     : base(scheduler, cache)
 {
     _optimizationInterfaces = optimizationInterfaces;
 }
Beispiel #39
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!this._isDisposed)
                {
                    bool disposeLock = false;
                    INotifyComposablePartCatalogChanged catalogToUnsubscribeFrom = null;
                    HashSet <IDisposable> partsToDispose = null;
                    ExportProvider        sourceProviderToUnsubscribeFrom = null;
                    ImportEngine          importEngineToDispose           = null;

                    try
                    {
                        using (this._lock.LockStateForWrite())
                        {
                            if (!this._isDisposed)
                            {
                                catalogToUnsubscribeFrom = this._catalog as INotifyComposablePartCatalogChanged;
                                this._catalog            = null;

                                sourceProviderToUnsubscribeFrom = this._sourceProvider;
                                this._sourceProvider            = null;

                                importEngineToDispose = this._importEngine;
                                this._importEngine    = null;

                                partsToDispose       = this._partsToDispose;
                                this._partsToDispose = new HashSet <IDisposable>();
                                this._activatedParts.Clear();
                                this._conditionalReferencesForRecomposableParts = null;

                                disposeLock      = true;
                                this._isDisposed = true;
                            }
                        }
                    }
                    finally
                    {
                        if (catalogToUnsubscribeFrom != null)
                        {
                            catalogToUnsubscribeFrom.Changing -= this.OnCatalogChanging;
                        }

                        if (sourceProviderToUnsubscribeFrom != null)
                        {
                            sourceProviderToUnsubscribeFrom.ExportsChanging -= this.OnExportsChangingInternal;
                        }

                        if (importEngineToDispose != null)
                        {
                            importEngineToDispose.Dispose();
                        }

                        if (partsToDispose != null)
                        {
                            foreach (var part in partsToDispose)
                            {
                                part.Dispose();
                            }
                        }

                        if (disposeLock)
                        {
                            this._lock.Dispose();
                        }
                    }
                }
            }
        }
 public SharpeMaximizer(IOptimizerConfiguration config, IFitnessFilter filter) : base(config, filter)
 {
     _resultIndex = new ConditionalWeakTable <OptimizerResult, string>();
 }
        private static void DebugPrintTo(Type type, object obj, Action <string> log, string indent, ConditionalWeakTable <object, Ref <bool> > table, int maxDepth)
        {
            if (maxDepth == 0)
            {
                log(indent + "<Max depth reached>");
                return;
            }

            if (obj == null)
            {
                log(indent + "null");
                return;
            }

            table.Add(obj, true);

            if (type.IsPrimitive)
            {
                log(indent + obj.ToString());
                return;
            }
            if (type.IsEnum)
            {
                log(indent + obj.ToString());
                return;
            }
            if (type == typeof(string))
            {
                log(indent + $"\"{obj.ToString()}\"");
                return;
            }
            if (type.IsArray)
            {
                log(indent + $"{type.GetElementType()} [");
                foreach (var o in obj as Array)
                {
                    if (type.GetElementType().IsPrimitive)
                    {
                        log(indent + "- " + o?.ToString() ?? "null");
                    }
                    else if (type.GetElementType().IsEnum)
                    {
                        log(indent + "- " + o?.ToString() ?? "null");
                    }
                    else if (type.GetElementType() == typeof(string))
                    {
                        log(indent + "- " + $"\"{o?.ToString()}\"");
                    }
                    else
                    {
                        log(indent + $"- {o?.GetType()?.ToString() ?? "null"}");
                        if (o != null)
                        {
                            if (!table.TryGetValue(o, out _))
                            {
                                DebugPrintTo(o.GetType(), o, log, indent + "  ", table, maxDepth - 1);
                            }
                            else
                            {
                                log(indent + "  <Already printed>");
                            }
                        }
                    }
                }
                log(indent + "]");
                return;
            }

            var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            foreach (var field in fields)
            {
                var value = field.GetValue(obj);

                if (field.FieldType.IsPrimitive)
                {
                    log(indent + field.Name + ": " + value?.ToString() ?? "null");
                }
                else if (field.FieldType.IsEnum)
                {
                    log(indent + field.Name + ": " + value?.ToString() ?? "null");
                }
                else if (field.FieldType == typeof(string))
                {
                    log(indent + field.Name + ": " + $"\"{value?.ToString()}\"");
                }
                else
                {
                    log(indent + field.Name + ": " + value?.GetType()?.ToString() ?? "null");
                    if (value != null)
                    {
                        if (!table.TryGetValue(value, out _))
                        {
                            DebugPrintTo(value?.GetType() ?? field.FieldType, value, log, indent + "  ", table, maxDepth - 1);
                        }
                        else
                        {
                            log(indent + "  <Already printed>");
                        }
                    }
                }
            }
        }
Beispiel #42
0
 //only used for unit testing
 internal static void ClearCache() => s_instances = new ConditionalWeakTable <Type, ResourceDictionary>();
Beispiel #43
0
 internal CompilationWithAnalyzers GetOrCreateCompilationWithAnalyzers(Project project, ConditionalWeakTable <Project, CompilationWithAnalyzers> .CreateValueCallback createCompilationWithAnalyzers)
 {
     Contract.ThrowIfFalse(project.SupportsCompilation);
     return(_compilationWithAnalyzersMap.GetValue(project, createCompilationWithAnalyzers));
 }
Beispiel #44
0
        public async Task When_Add_Remove(object controlTypeRaw, int count)
        {
#if TRACK_REFS
            var initialInactiveStats = Uno.UI.DataBinding.BinderReferenceHolder.GetInactiveViewReferencesStats();
            var initialActiveStats   = Uno.UI.DataBinding.BinderReferenceHolder.GetReferenceStats();
#endif

            Type GetType(string s)
            => AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType(s)).Where(t => t != null).First() !;

            var controlType = controlTypeRaw switch
            {
                Type ct => ct,
                string s => GetType(s),
                _ => throw new InvalidOperationException()
            };

            var _holders = new ConditionalWeakTable <DependencyObject, Holder>();
            void TrackDependencyObject(DependencyObject target) => _holders.Add(target, new Holder(HolderUpdate));

            var maxCounter        = 0;
            var activeControls    = 0;
            var maxActiveControls = 0;

            var rootContainer = new ContentControl();

            TestServices.WindowHelper.WindowContent = rootContainer;

            await TestServices.WindowHelper.WaitForIdle();

            for (int i = 0; i < count; i++)
            {
                await MaterializeControl(controlType, _holders, maxCounter, rootContainer);
            }

            TestServices.WindowHelper.WindowContent = null;

            void HolderUpdate(int value)
            {
                _ = rootContainer.Dispatcher.RunAsync(CoreDispatcherPriority.High,
                                                      () =>
                {
                    maxCounter        = Math.Max(value, maxCounter);
                    activeControls    = value;
                    maxActiveControls = maxCounter;
                }
                                                      );
            }

            var sw                 = Stopwatch.StartNew();
            var endTime            = TimeSpan.FromSeconds(30);
            var maxTime            = TimeSpan.FromMinutes(1);
            var lastActiveControls = activeControls;

            while (sw.Elapsed < endTime && sw.Elapsed < maxTime && activeControls != 0)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();

                // Waiting for idle is required for collection of
                // DispatcherConditionalDisposable to be executed
                await TestServices.WindowHelper.WaitForIdle();

                if (lastActiveControls != activeControls)
                {
                    // Expand the timeout if the count has changed, as the
                    // GC may still be processing levels of the hierarcy on iOS
                    endTime += TimeSpan.FromMilliseconds(500);
                }

                lastActiveControls = activeControls;
            }

#if TRACK_REFS
            Uno.UI.DataBinding.BinderReferenceHolder.LogInactiveViewReferencesStatsDiff(initialInactiveStats);
            Uno.UI.DataBinding.BinderReferenceHolder.LogActiveViewReferencesStatsDiff(initialActiveStats);
#endif

            var retainedMessage = "";

#if NET5_0 || __IOS__ || __ANDROID__
            if (activeControls != 0)
            {
                var retainedTypes = _holders.AsEnumerable().Select(ExtractTargetName).JoinBy(";");
                Console.WriteLine($"Retained types: {retainedTypes}");

                retainedMessage = $"Retained types: {retainedTypes}";
            }
#endif

#if __IOS__
            // On iOS, the collection of objects does not seem to be reliable enough
            // to always go to zero during runtime tests. If the count of active objects
            // is arbitrarily below the half of the number of top-level objects.
            // created, we can assume that enough objects were collected entirely.
            Assert.IsTrue(activeControls < count, retainedMessage);
#else
            Assert.AreEqual(0, activeControls, retainedMessage);
 internal DiagnosticAnalyzerInfoCache()
 {
     _descriptorsInfo = new ConditionalWeakTable <DiagnosticAnalyzer, DiagnosticDescriptorsInfo>();
 }
Beispiel #46
0
            async Task MaterializeControl(Type controlType, ConditionalWeakTable <DependencyObject, Holder> _holders, int maxCounter, ContentControl rootContainer)
            {
                var item = (FrameworkElement)Activator.CreateInstance(controlType);

                TrackDependencyObject(item);
                rootContainer.Content = item;
                await TestServices.WindowHelper.WaitForIdle();

                // Add all children to the tracking
                foreach (var child in item.EnumerateAllChildren(maxDepth: 200).OfType <UIElement>())
                {
                    TrackDependencyObject(child);

                    if (child is FrameworkElement fe)
                    {
                        // Don't use VisualStateManager.GetVisualStateManager to avoid creating an instance
                        if (child.GetValue(VisualStateManager.VisualStateManagerProperty) is VisualStateManager vsm)
                        {
                            TrackDependencyObject(vsm);

                            if (VisualStateManager.GetVisualStateGroups(fe) is { } groups)
                            {
                                foreach (var group in groups)
                                {
                                    TrackDependencyObject(group);

                                    foreach (var transition in group.Transitions)
                                    {
                                        TrackDependencyObject(transition);

                                        foreach (var timeline in transition.Storyboard.Children)
                                        {
                                            TrackDependencyObject(timeline);
                                        }
                                    }

                                    foreach (var state in group.States)
                                    {
                                        TrackDependencyObject(state);

                                        foreach (var setter in state.Setters)
                                        {
                                            TrackDependencyObject(setter);
                                        }

                                        foreach (var trigger in state.StateTriggers)
                                        {
                                            TrackDependencyObject(trigger);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                rootContainer.Content = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();

                // Waiting for idle is required for collection of
                // DispatcherConditionalDisposable to be executed
                await TestServices.WindowHelper.WaitForIdle();
            }
Beispiel #47
0
 /// <summary>
 /// Create an instance of this class.
 /// </summary>
 public StackTraceSymbols()
 {
     _metadataCache = new ConditionalWeakTable <Assembly, MetadataReaderProvider?>();
 }
Beispiel #48
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!_isDisposed)
                {
                    //Note:  We do not dispose _lock on dispose because DisposePart needs it to check isDisposed state
                    //          to eliminate race conditions between it and Dispose
                    INotifyComposablePartCatalogChanged catalogToUnsubscribeFrom = null;
                    HashSet <IDisposable>   partsToDispose          = null;
                    ImportEngine            importEngine            = null;
                    ExportProvider          sourceProvider          = null;
                    AggregateExportProvider aggregateExportProvider = null;
                    try
                    {
                        using (_lock.LockStateForWrite())
                        {
                            if (!_isDisposed)
                            {
                                catalogToUnsubscribeFrom = _catalog as INotifyComposablePartCatalogChanged;
                                _catalog = null;

                                aggregateExportProvider = _innerExportProvider as AggregateExportProvider;
                                _innerExportProvider    = null;

                                sourceProvider  = _sourceProvider;
                                _sourceProvider = null;

                                importEngine  = _importEngine;
                                _importEngine = null;

                                partsToDispose = _partsToDispose;
                                _gcRoots       = null;
                                _isDisposed    = true;
                            }
                        }
                    }
                    finally
                    {
                        if (catalogToUnsubscribeFrom != null)
                        {
                            catalogToUnsubscribeFrom.Changing -= OnCatalogChanging;
                        }

                        if (aggregateExportProvider != null)
                        {
                            aggregateExportProvider.Dispose();
                        }

                        if (sourceProvider != null)
                        {
                            sourceProvider.ExportsChanging -= OnExportsChangingInternal;
                        }

                        if (importEngine != null)
                        {
                            importEngine.Dispose();
                        }

                        if (partsToDispose != null)
                        {
                            foreach (var part in partsToDispose)
                            {
                                part.Dispose();
                            }
                        }
                    }
                }
            }
        }
Beispiel #49
0
        private ProjectId?GetProjectIdDirectly(
            ISymbol symbol, ConditionalWeakTable <ISymbol, ProjectId?> unrootedSymbolToProjectId)
        {
            if (symbol.IsKind(SymbolKind.Namespace, out INamespaceSymbol? ns))
            {
                if (ns.ContainingCompilation != null)
                {
                    // A namespace that spans a compilation.  These don't belong to an assembly/module directly.
                    // However, as we're looking for the project this corresponds to, we can look for the
                    // source-module component (the first in the constituent namespaces) and then search using that.
                    return(GetOriginatingProjectId(ns.ConstituentNamespaces[0]));
                }
            }
            else if (symbol.IsKind(SymbolKind.Assembly) ||
                     symbol.IsKind(SymbolKind.NetModule) ||
                     symbol.IsKind(SymbolKind.DynamicType))
            {
                if (!unrootedSymbolToProjectId.TryGetValue(symbol, out var projectId))
                {
                    // First, look through all the projects, and see if this symbol came from the primary assembly for
                    // that project.  (i.e. was a source symbol from that project, or was retargetted into that
                    // project).  If so, that's the originating project.
                    //
                    // If we don't find any primary results, then look through all the secondary assemblies (i.e.
                    // references) for that project.  This is the case for metadata symbols.  A metadata symbol might be
                    // found in many projects, so we just return the first result as that's just as good for finding the
                    // metadata symbol as any other project.
                    projectId = TryGetProjectId(symbol, primary: true) ??
                                TryGetProjectId(symbol, primary: false);

                    // Have to lock as there's no atomic AddOrUpdate in netstandard2.0 and we could throw if two
                    // threads tried to add the same item.
#if !NETCOREAPP
                    lock (unrootedSymbolToProjectId)
                    {
                        unrootedSymbolToProjectId.Remove(symbol);
                        unrootedSymbolToProjectId.Add(symbol, projectId);
                    }
#else
                    unrootedSymbolToProjectId.AddOrUpdate(symbol, projectId);
#endif
                }

                return(projectId);
            }
            else if (symbol.IsKind(SymbolKind.TypeParameter, out ITypeParameterSymbol? typeParameter) &&
                     typeParameter.TypeParameterKind == TypeParameterKind.Cref)
            {
                // Cref type parameters don't belong to any containing symbol.  But we can map them to a doc/project
                // using the declaring syntax of the type parameter itself.
                var tree = typeParameter.Locations[0].SourceTree;
                var doc  = this.GetDocumentState(tree, projectId: null);
                return(doc?.Id.ProjectId);
            }

            return(null);

            ProjectId?TryGetProjectId(ISymbol symbol, bool primary)
            {
                foreach (var(id, tracker) in _projectIdToTrackerMap)
                {
                    if (tracker.ContainsAssemblyOrModuleOrDynamic(symbol, primary))
                    {
                        return(id);
                    }
                }

                return(null);
            }
        }
Beispiel #50
0
 public static ITable <TIn, TOut> ToTable <TIn, TOut>(this ConditionalWeakTable <TIn, Tuple <TOut> > @this)
     where TIn : class where TOut : struct
 => StructureValueTables <TIn, TOut> .Default.Get(@this);
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!this._isDisposed)
                {
                    bool disposeLock = false;
                    INotifyComposablePartCatalogChanged catalogToUnsubscribeFrom = null;
                    HashSet <IDisposable>   partsToDispose          = null;
                    ImportEngine            importEngine            = null;
                    ExportProvider          sourceProvider          = null;
                    AggregateExportProvider aggregateExportProvider = null;
                    try
                    {
                        using (this._lock.LockStateForWrite())
                        {
                            if (!this._isDisposed)
                            {
                                catalogToUnsubscribeFrom = this._catalog as INotifyComposablePartCatalogChanged;
                                this._catalog            = null;

                                aggregateExportProvider   = this._innerExportProvider as AggregateExportProvider;
                                this._innerExportProvider = null;

                                sourceProvider       = this._sourceProvider;
                                this._sourceProvider = null;

                                importEngine       = this._importEngine;
                                this._importEngine = null;

                                partsToDispose = this._partsToDispose;
                                this._gcRoots  = null;

                                disposeLock      = true;
                                this._isDisposed = true;
                            }
                        }
                    }
                    finally
                    {
                        if (catalogToUnsubscribeFrom != null)
                        {
                            catalogToUnsubscribeFrom.Changing -= this.OnCatalogChanging;
                        }

                        if (aggregateExportProvider != null)
                        {
                            aggregateExportProvider.Dispose();
                        }

                        if (sourceProvider != null)
                        {
                            sourceProvider.ExportsChanging -= this.OnExportsChangingInternal;
                        }

                        if (importEngine != null)
                        {
                            importEngine.Dispose();
                        }

                        if (partsToDispose != null)
                        {
                            foreach (var part in partsToDispose)
                            {
                                part.Dispose();
                            }
                        }

                        if (disposeLock)
                        {
                            this._lock.Dispose();
                        }
                    }
                }
            }
        }
Beispiel #52
0
 public static ITable <TIn, TOut> ToTable <TIn, TOut>(this ConditionalWeakTable <TIn, TOut> @this)
     where TOut : class where TIn : class
 => ReferenceValueTables <TIn, TOut> .Default.Get(@this);
 public static Checksum GetOrCreate(object value, ConditionalWeakTable <object, object> .CreateValueCallback checksumCreator)
 {
     // same key should always return same checksum
     return((Checksum)s_cache.GetValue(value, checksumCreator));
 }
Beispiel #54
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PropertyObserver"/> class.
 /// </summary>
 public PropertyObserver()
 {
     table = new ConditionalWeakTable <INotifyPropertyChanged, Subscriber>();
 }
 public FinalizableLink(int id, object obj, ConditionalWeakTable <object, object> cwt)
 {
     this.id  = id;
     this.obj = obj;
     this.cwt = cwt;
 }
Beispiel #56
0
 private static SemanticModel?GetCachedSemanticModel(ConditionalWeakTable <SyntaxNode, WeakReference <SemanticModel> > nodeMap, SyntaxNode newMember)
 => nodeMap.TryGetValue(newMember, out var cached) && cached.TryGetTarget(out var model) ? model : null;
Beispiel #57
0
 internal TokenCache(byte[] data)
 {
     _data           = data;
     _lastUpdated    = DateTimeOffset.UtcNow;
     _cacheAccessMap = new ConditionalWeakTable <object, CacheTimestamp>();
 }
Beispiel #58
0
        private static async Task GetDependentTypesInProjectAsync(
            INamedTypeSymbol type, Project project, Solution solution, Func <INamedTypeSymbol, INamedTypeSymbol, bool> predicate, ConditionalWeakTable <Compilation, ConcurrentDictionary <SymbolKey, List <SymbolKey> > > cache, bool locationsInMetadata, ConcurrentSet <ISymbol> results, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);

            var typeId = type.GetSymbolKey();

            List <SymbolKey> dependentTypeIds;

            if (!TryGetDependentTypes(cache, compilation, typeId, out dependentTypeIds))
            {
                List <INamedTypeSymbol> allTypes;
                if (locationsInMetadata)
                {
                    // From metadata, have to check other (non private) metadata types, as well as
                    // source types.
                    allTypes = GetAllSourceAndAccessibleTypesInCompilation(compilation, cancellationToken);
                }
                else
                {
                    // It's from source, so only other source types could derive from it.
                    allTypes = GetAllSourceTypesInCompilation(compilation, cancellationToken);
                }

                dependentTypeIds = new List <SymbolKey>();
                foreach (var t in allTypes)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    if (predicate(t, type))
                    {
                        dependentTypeIds.Add(t.GetSymbolKey());
                    }
                }

                dependentTypeIds = GetOrAddDependentTypes(cache, compilation, typeId, dependentTypeIds);
            }

            foreach (var id in dependentTypeIds)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var resolvedSymbols = id.Resolve(compilation, cancellationToken: cancellationToken).GetAllSymbols();
                foreach (var resolvedSymbol in resolvedSymbols)
                {
                    var mappedSymbol = await SymbolFinder.FindSourceDefinitionAsync(resolvedSymbol, solution, cancellationToken).ConfigureAwait(false) ?? resolvedSymbol;

                    results.Add(mappedSymbol);
                }
            }
        }
 /// <summary>
 /// Creates a new JavaScript engine.
 /// </summary>
 public JavaScriptEngine()
 {
     _contexts = new ConditionalWeakTable<IWindow, EngineInstance>();
     _external = new Dictionary<String, Object>();
 }
Beispiel #60
0
 private DiagnosticAnalyzerService()
 {
     _map = new ConditionalWeakTable <Workspace, BaseDiagnosticIncrementalAnalyzer>();
     _createIncrementalAnalyzer = CreateIncrementalAnalyzerCallback;
 }