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); } }
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); }
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); }
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); }
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 }
public string GetNameForFunctionImpl(Function function) { if (funcNames.TryGetValue(function, out string name)) { return(name); } string namePrefix = NamePrefix; string methodName = function.IsAnon ? "Anon" : function.Name; string nameSuffix = "_IMPL"; name = UniquifyName(namePrefix + methodName + nameSuffix); funcNames.Add(function, name); return(name); }
static public MeshMaterialData Get(Mesh meshToGetMaterialDataFor) { MeshMaterialData plugin; meshsWithMaterialData.TryGetValue(meshToGetMaterialDataFor, out plugin); if (plugin == null) { MeshMaterialData newPlugin = new MeshMaterialData(); meshsWithMaterialData.Add(meshToGetMaterialDataFor, newPlugin); return(newPlugin); } return(plugin); }
/// <summary> /// Gets a <see cref="SurfaceLoader"/> instance for a given <see cref="Compositor"/> /// </summary> /// <param name="compositor">The input <see cref="Compositor"/> object to use</param> /// <returns>A <see cref="SurfaceLoader"/> instance associated with <paramref name="compositor"/></returns> public static SurfaceLoader GetInstance(Compositor compositor) { lock (Instances) { if (Instances.TryGetValue(compositor, out var instance)) { return(instance); } instance = new SurfaceLoader(compositor); Instances.Add(compositor, instance); return(instance); } }
static public FaceEdgeTextureUvData Get(FaceEdge faceEdgeToGetTextureUvDataFor) { FaceEdgeTextureUvData plugin; faceEdgesWithTextureUvData.TryGetValue(faceEdgeToGetTextureUvDataFor, out plugin); if (plugin == null) { FaceEdgeTextureUvData newPlugin = new FaceEdgeTextureUvData(); faceEdgesWithTextureUvData.Add(faceEdgeToGetTextureUvDataFor, newPlugin); return(newPlugin); } return(plugin); }
public static void InvalidArgs_Throws() { var cwt = new ConditionalWeakTable <object, object>(); object ignored; AssertExtensions.Throws <ArgumentNullException>("key", () => cwt.Add(null, new object())); // null key AssertExtensions.Throws <ArgumentNullException>("key", () => cwt.TryGetValue(null, out ignored)); // null key AssertExtensions.Throws <ArgumentNullException>("key", () => cwt.Remove(null)); // null key AssertExtensions.Throws <ArgumentNullException>("createValueCallback", () => cwt.GetValue(new object(), null)); // null delegate object key = new object(); cwt.Add(key, key); AssertExtensions.Throws <ArgumentException>(null, () => cwt.Add(key, key)); // duplicate key }
/// <summary> /// Create the child ContentPresenter for the given item (could be data or a TabItem) /// </summary> /// <param name="item">The item.</param> private void CreateChildContentPresenter(object item) { if (item == null) { return; } object dummyObject = null; if (_wrappedContainers.TryGetValue(item, out dummyObject)) { return; } _wrappedContainers.Add(item, new object()); var cp = FindChildContentPresenter(item); if (cp != null) { return; } // the actual child to be added. cp.Tag is a reference to the TabItem cp = new ContentPresenter(); var container = GetContentContainer(item); var content = GetContent(item); var tabItemData = new TabControlItemData(container, content, ContentTemplate, item); #pragma warning disable WPF0041 // Set mutable dependency properties using SetCurrentValue. cp.Tag = tabItemData; #pragma warning restore WPF0041 // Set mutable dependency properties using SetCurrentValue. if (!IsLazyLoading) { ShowChildContent(cp, tabItemData); } #pragma warning disable WPF0041 // Set mutable dependency properties using SetCurrentValue. cp.ContentTemplateSelector = ContentTemplateSelector; cp.ContentStringFormat = SelectedContentStringFormat; #pragma warning restore WPF0041 // Set mutable dependency properties using SetCurrentValue. _itemsHolder.Children.Add(cp); }
private async Task <IEnumerable <CompletionItem> > GetItemsWorkerAsync( Document document, int position, OptionSet options, bool preselect, CancellationToken cancellationToken) { var relatedDocumentIds = document.GetLinkedDocumentIds(); var relatedDocuments = relatedDocumentIds.Concat(document.Id).Select(document.Project.Solution.GetDocument); lock (s_cacheGate) { // Invalidate the cache if it's for a different position or a different set of Documents. // It's fairly likely that we'll only have to check the first document, unless someone // specially constructed a Solution with mismatched linked files. Task <SyntaxContext> value; if (s_cachedPosition != position || !relatedDocuments.All((Document d) => s_cachedDocuments.TryGetValue(d, out value))) { s_cachedPosition = position; foreach (var related in relatedDocuments) { s_cachedDocuments.Remove(document); } } } var context = await GetOrCreateContext(document, position, cancellationToken).ConfigureAwait(false); options = GetUpdatedRecommendationOptions(options, document.Project.Language); if (!relatedDocumentIds.Any()) { IEnumerable <ISymbol> itemsForCurrentDocument = await GetSymbolsWorker(position, preselect, context, options, cancellationToken).ConfigureAwait(false); itemsForCurrentDocument = itemsForCurrentDocument ?? SpecializedCollections.EmptyEnumerable <ISymbol>(); return(CreateItems(itemsForCurrentDocument, context, invalidProjectMap: null, totalProjects: null, preselect: preselect)); } var contextAndSymbolLists = await GetPerContextSymbols(document, position, options, new[] { document.Id }.Concat(relatedDocumentIds), preselect, cancellationToken).ConfigureAwait(false); Dictionary <ISymbol, SyntaxContext> originatingContextMap = null; var unionedSymbolsList = UnionSymbols(contextAndSymbolLists, out originatingContextMap); var missingSymbolsMap = FindSymbolsMissingInLinkedContexts(unionedSymbolsList, contextAndSymbolLists); var totalProjects = contextAndSymbolLists.Select(t => t.Item1.ProjectId).ToList(); return(CreateItems(unionedSymbolsList, originatingContextMap, missingSymbolsMap, totalProjects, preselect)); }
private static void UpdateSpawners(SpawnSystem self, bool eventSpawners) { if (Instances.TryGetValue(self, out var goodSpawnSystem)) { var activeSpawnersForBiome = goodSpawnSystem.Spawners.List.Where(spawner => spawner.Item.m_enabled && self.m_heightmap.HaveBiome(spawner.Item.m_biome)).ToList(); var spawner = goodSpawnSystem.Spawners.GetRandomItem(activeSpawnersForBiome); if ((!string.IsNullOrEmpty(spawner.m_requiredGlobalKey) && !ZoneSystem.instance.GetGlobalKey(spawner.m_requiredGlobalKey)) || (spawner.m_requiredEnvironments.Count > 0 && !EnvMan.instance.IsEnvironment(spawner.m_requiredEnvironments)) || (!spawner.m_spawnAtDay && EnvMan.instance.IsDay()) || (!spawner.m_spawnAtNight && EnvMan.instance.IsNight()) || SpawnSystem.GetNrOfInstances(spawner.m_prefab, Vector3.zero, 0f, eventSpawners, false) >= spawner.m_maxSpawned) { return; } if (self.FindBaseSpawnPoint(spawner, self.m_nearPlayers, out var vector, out var player) && (spawner.m_spawnDistance <= 0f || !SpawnSystem.HaveInstanceInRange(spawner.m_prefab, vector, spawner.m_spawnDistance))) { var groupSize = UnityEngine.Random.Range(spawner.m_groupSizeMin, spawner.m_groupSizeMax + 1); var groupRadius = groupSize > 1 ? spawner.m_groupRadius : 0f; var numberOfSpawnedMonsters = 0; for (var i = 0; i < groupSize * 2; i++) { var insideUnitCircle = UnityEngine.Random.insideUnitCircle; var spawnPoint = vector + new Vector3(insideUnitCircle.x, 0f, insideUnitCircle.y) * groupRadius; if (self.IsSpawnPointGood(spawner, ref spawnPoint)) { self.Spawn(spawner, spawnPoint + Vector3.up * spawner.m_groundOffset, eventSpawners); numberOfSpawnedMonsters++; if (numberOfSpawnedMonsters >= groupSize) { break; } } } Log.LogInfo($"Spawned {numberOfSpawnedMonsters} {spawner.m_prefab.name}"); } } else { Log.LogWarning($"Failed to find a spawner list for : {self.name}"); } }
public void RemoveTarget(EventHandler notification, UIControlEvent events) { #if XAMCORE_2_0 Dictionary <EventHandler, Dictionary <UIControlEvent, UIControlEventProxy> > targets; if (allTargets == null) { return; } if (!allTargets.TryGetValue(this, out targets)) { return; } #else if (targets == null) { return; } #endif Dictionary <UIControlEvent, UIControlEventProxy> t; if (!targets.TryGetValue(notification, out t)) { return; } UIControlEventProxy ep; if (!t.TryGetValue(events, out ep)) { return; } ep.Counter--; if (ep.Counter > 1) { return; } RemoveTarget(ep, Selector.GetHandle(UIControlEventProxy.BridgeSelector), events); t.Remove(events); ep.Dispose(); if (t.Count == 0) { targets.Remove(notification); } }
private object getOrCreatePO(POIdentifier id, Type t) { //NOTE: use getIdentifier to get the correct id instance, to ensure that the weaktable keeps working //TODO: provide factory //TODO: Note that objects are not removed from the identity cache after serialization, so are reuse on deserialization! //TODO: provide a way to remove objects from the cache? object po; if (pos.TryGetValue(getIdentifier(id.Guid), out po)) { return(po); } po = Activator.CreateInstance(t); pos.Add(getIdentifier(id.Guid), po); ids.Add(po, getIdentifier(id.Guid)); return(po); }
private void diagramView_KeyDown(object sender, KeyEventArgs e) { if (e.Control && e.KeyCode == Keys.C) { var shapeNode = treeDiagram.ActiveItem as ShapeNode; if (shapeNode == null) { return; } if (VisNodeTable.TryGetValue(shapeNode, out var visNode)) { //TODO Remove the reference to the debugging of the debugger visualiser from Test var XMindString = new XMindVisualiser(visNode).GetTree(); Clipboard.SetText(XMindString); } } }
public SyntaxAnnotation[] GetAnnotations() { if (this.ContainsAnnotations) { SyntaxAnnotation[]? annotations; if (s_annotationsTable.TryGetValue(this, out annotations)) { System.Diagnostics.Debug.Assert( annotations.Length != 0, "we should return nonempty annotations or NoAnnotations" ); return(annotations); } } return(s_noAnnotations); }
internal void ClearAnalyzerExceptionHandlers(DiagnosticAnalyzer analyzer) { // Host is disposing the analyzer instance, unsubscribe analyzer exception handlers. Tuple <ImmutableArray <DiagnosticDescriptor>, EventHandler <Exception> > value; if (_descriptorCache.TryGetValue(analyzer, out value)) { var descriptors = value.Item1; var handler = value.Item2; foreach (var descriptor in descriptors) { descriptor.Title.OnException -= handler; descriptor.MessageFormat.OnException -= handler; descriptor.Description.OnException -= handler; } } }
public static string GetId(object value) { if (value == null) { throw new ArgumentNullException("value"); } string id; if (!identifiers.TryGetValue(value, out id)) { id = Guid.NewGuid().ToString(); identifiers.Add(value, id); } return(id); }
private IAnalysisSet ContextClassProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { var dict = GetArg(args, keywordArgNames, "dict_", 0); if (dict != null && dict.Any()) { ContextMarker contextValue; if (!_contextTable.TryGetValue(node, out contextValue)) { contextValue = new ContextMarker(); _contextTable.Add(node, contextValue); } contextValue.Arguments.UnionWith(dict); return contextValue; } return AnalysisSet.Empty; }
public void OldGenKeysMakeNewGenObjectsReachable() { if (GC.MaxGeneration == 0) /*Boehm doesn't handle ephemerons */ { Assert.Ignore("Not working on Boehm."); } ConditionalWeakTable <object, Val> table = new ConditionalWeakTable <object, Val>(); List <Key> keys = new List <Key>(); // // This list references all keys for the duration of the program, so none // should be collected ever. // for (int x = 0; x < 1000; x++) { keys.Add(new Key() { Foo = x }); } for (int i = 0; i < 1000; ++i) { // Insert all keys into the ConditionalWeakTable foreach (var key in keys) { table.Add(key, new Val() { Foo = key.Foo }); } // Look up all keys to verify that they are still there Val val; foreach (var key in keys) { Assert.IsTrue(table.TryGetValue(key, out val), "#1-" + i + "-k-" + key); } // Remove all keys from the ConditionalWeakTable foreach (var key in keys) { Assert.IsTrue(table.Remove(key), "#2-" + i + "-k-" + key); } } }
private void UpdatePresentation(object item) { ContentPresenter ctp = null; if (item != null) { if (!_PresenterCache.TryGetValue(item, out ctp)) { ctp = new ContentPresenter { ContentTemplate = DataTemplate }; ctp.SetBinding(ContentPresenter.ContentProperty, new Binding()); _PresenterCache.Add(item, ctp); } } this.Child = ctp; }
public static async Task <SyntaxTreeIndex> GetIndexAsync( Document document, CancellationToken cancellationToken) { // See if we already cached an index with this direct document index. If so we can just // return it with no additional work. if (!s_documentToIndex.TryGetValue(document, out var index)) { index = await GetIndexWorkerAsync(document, cancellationToken).ConfigureAwait(false); // Populate our caches with this data. s_documentToIndex.GetValue(document, _ => index); s_documentIdToIndex.GetValue(document.Id, _ => index); } return(index); }
public static CompoundParameterContext GetContext( [NotNull] ICompoundParameter compoundParameter) { if (compoundParameter is null) { throw new ArgumentNullException(nameof(compoundParameter)); } bool result = _contexts.TryGetValue(compoundParameter, out var context); if (!result) { throw new ArgumentException(); } return(context); }
public static JavaProxyObject?GetProxy(object value) { if (value == null) { return(null); } lock (CachedValues) { if (CachedValues.TryGetValue(value, out var proxy)) { return(proxy); } proxy = new JavaProxyObject(value); CachedValues.Add(value, proxy); return(proxy); } }
/// <exception cref="System.IO.IOException"></exception> public virtual ShapeFieldCache <T> GetCache(AtomicReader reader) { lock (locker) { ShapeFieldCache <T> idx; if (sidx.TryGetValue(reader, out idx) && idx != null) { return(idx); } /*long startTime = Runtime.CurrentTimeMillis(); * log.Fine("Building Cache [" + reader.MaxDoc() + "]");*/ idx = new ShapeFieldCache <T>(reader.MaxDoc, defaultSize); int count = 0; DocsEnum docs = null; Terms terms = reader.Terms(shapeField); TermsEnum te = null; if (terms != null) { te = terms.Iterator(te); BytesRef term = te.Next(); while (term != null) { T shape = ReadShape(term); if (shape != null) { docs = te.Docs(null, docs, DocsEnum.FLAG_NONE); int docid = docs.NextDoc(); while (docid != DocIdSetIterator.NO_MORE_DOCS) { idx.Add(docid, shape); docid = docs.NextDoc(); count++; } } term = te.Next(); } } sidx.Add(reader, idx); /*long elapsed = Runtime.CurrentTimeMillis() - startTime; * log.Fine("Cached: [" + count + " in " + elapsed + "ms] " + idx);*/ return(idx); } }
public static void Add(int numObjects, bool tryAdd) { // 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++) { if (tryAdd) { Assert.True(cwt.TryAdd(keys[i], values[i])); } else { 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}"); } }
private VSCompletionItem Convert( Document document, RoslynCompletionItem roslynItem) { if (roslynItem.IsCached && s_roslynItemToVsItem.TryGetValue(roslynItem, out var vsItem)) { return(vsItem); } var imageId = roslynItem.Tags.GetFirstGlyph().GetImageId(); var filters = GetFilters(roslynItem); // roslynItem generated by providers can contain an insertionText in a property bag. // We will not use it but other providers may need it. // We actually will calculate the insertion text once again when called TryCommit. if (!roslynItem.Properties.TryGetValue(InsertionText, out var insertionText)) { insertionText = roslynItem.DisplayText; } var supportedPlatforms = SymbolCompletionItem.GetSupportedPlatforms(roslynItem, document.Project.Solution.Workspace); var attributeImages = supportedPlatforms != null ? s_WarningImageAttributeImagesArray : ImmutableArray <ImageElement> .Empty; var item = new VSCompletionItem( displayText: roslynItem.GetEntireDisplayText(), source: this, icon: new ImageElement(new ImageId(imageId.Guid, imageId.Id), roslynItem.DisplayText), filters: filters, suffix: roslynItem.InlineDescription, // InlineDescription will be right-aligned in the selection popup insertText: insertionText, sortText: roslynItem.SortText, filterText: roslynItem.FilterText, attributeIcons: attributeImages); item.Properties.AddProperty(RoslynItem, roslynItem); // It doesn't make sense to cache VS item for those Roslyn items created from scratch for each session, // since CWT uses object identity for comparison. if (roslynItem.IsCached) { s_roslynItemToVsItem.Add(roslynItem, item); } return(item); }
public static byte[] GetHash(string item) { if (item == null) { throw new ArgumentNullException("item"); } try { lock (_hashCacheLockObject) { byte[] value; if (!_hashCache.TryGetValue(item, out value)) { var index = item.LastIndexOf('@'); if (index == -1) { return(null); } var nickname = item.Substring(0, index); var hash = item.Substring(index + 1); if (nickname.Length > 256) { return(null); } if (hash.Length > 256 || !Signature.CheckBase64(hash)) { return(null); } value = NetworkConverter.FromBase64UrlString(hash); _hashCache.Add(item, value); } return(value); } } catch (Exception) { return(null); } }
/// <summary> /// this gives you SymbolTreeInfo for a project /// </summary> public static async Task <SymbolTreeInfo> GetInfoForProjectAsync(Project project, CancellationToken cancellationToken) { if (!project.SupportsCompilation) { return(null); } var branchId = project.Solution.BranchId; var workspace = project.Solution.Workspace; ConditionalWeakTable <ProjectId, SymbolTreeInfo> infoTable; if (!inMemoryCache.TryGetValue(branchId, out infoTable)) { infoTable = inMemoryCache.GetValue(branchId, id => new ConditionalWeakTable <ProjectId, SymbolTreeInfo>()); } // version doesn't need to know about dependent projects since we only care about names of top level declarations. var version = await project.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false); // first look to see if we already have the info SymbolTreeInfo info; if (infoTable.TryGetValue(project.Id, out info) && info != null && info.version == version) { return(info); } infoTable.Remove(project.Id); // next, either get the info from the persistent service or create one var persistAndInfo = await LoadOrCreateAsync(project, cancellationToken).ConfigureAwait(false); var persisted = persistAndInfo.Item1; var newInfo = persistAndInfo.Item2; if (!persisted || ShouldCache(project)) { // there could be someone already have put something in here. infoTable.GetValue(project.Id, _ => newInfo); } // use the info we calculated. otherwise, we can encounter a race. return(newInfo); }
private static void Player_Update(On.Celeste.Player.orig_Update orig, Player self) { DreamDashController controller = self.Scene.Tracker.GetEntity <DreamDashController>(); if (controller != null) { if (Input.Dash.Pressed && Input.Aim.Value != Vector2.Zero) { controller.dreamDashRedirect(self); } } Facings preOrigFacing = self.Facing; Vector2 preOrigScale = self.Sprite.Scale; orig(self); if (wallPlayerRotations.TryGetValue(self, out var rotationHolder)) { self.Facing = preOrigFacing; self.Sprite.Scale = preOrigScale; Vector2 inputAim = Input.Aim.Value; if (inputAim != Vector2.Zero) { float inputAngleOffset = (inputAim.Angle() - rotationHolder.value + MathHelper.TwoPi) % MathHelper.TwoPi; Facings newFacing = self.Facing; if (inputAngleOffset >= Math.PI * 0.75 && inputAngleOffset <= Math.PI * 1.25) { newFacing = Facings.Left; } else if (inputAngleOffset >= Math.PI * -0.25 && inputAngleOffset <= Math.PI * 0.25 || inputAngleOffset - MathHelper.TwoPi >= Math.PI * -0.25 && inputAngleOffset - MathHelper.TwoPi <= Math.PI * 0.25) { newFacing = Facings.Right; } if (self.Facing != newFacing) { self.Facing = newFacing; } } } }
public void ExecCallback(object param) { if (!IsSubscriberAlive || Subscriber == null) { return; } Action callback; if (_subscriberMethod.TryGetValue(Subscriber, out callback)) { callback(); } else if (_method != null) { _method.Invoke(Subscriber, new [] { param }); } }
public override void CancelWorkForView(object view) { lock (s_viewsReferences) { if (s_viewsReferences.TryGetValue(view, out var existingTask)) { try { if (existingTask != null && !existingTask.IsCancelled && !existingTask.IsCompleted) { existingTask.Cancel(); } } catch (ObjectDisposedException) { } s_viewsReferences.Remove(view); } } }
internal static bool TryGetMetricManager(this TelemetryClient telemetryClient, out MetricManager metricManager) { if (telemetryClient == null) { metricManager = null; return(false); } ConditionalWeakTable <TelemetryClient, MetricManager> metricManagers = metricManagersForTelemetryClients; if (metricManagers == null) { metricManager = null; return(false); } return(metricManagers.TryGetValue(telemetryClient, out metricManager)); }
public static LinkerConfiguration GetInstance(LinkContext context, bool createIfNotFound = true) { if (!configurations.TryGetValue(context, out var instance) && createIfNotFound) { if (!context.TryGetCustomData("LinkerOptionsFile", out var linker_options_file)) { throw new Exception($"No custom linker options file was passed to the linker (using --custom-data LinkerOptionsFile=..."); } instance = new LinkerConfiguration(linker_options_file) { Context = context, }; configurations.Add(context, instance); } return(instance); }
// 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)); }
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}"); } }
private static List<InstanceInitializationData> GetListForCurrentRequest( ConditionalWeakTable<HttpContext, List<InstanceInitializationData>> dictionary) { HttpContext currentRequest = HttpContext.Current; if (currentRequest == null) { return new List<InstanceInitializationData>(); } lock (dictionary) { List<InstanceInitializationData> currentRequestInstances; if (!dictionary.TryGetValue(currentRequest, out currentRequestInstances)) { dictionary.Add(currentRequest, currentRequestInstances = new List<InstanceInitializationData>(capacity: 32)); } return currentRequestInstances; } }
private static bool TryGetDependentTypes(ConditionalWeakTable<Compilation, ConcurrentDictionary<SymbolKey, List<SymbolKey>>> cache, Compilation compilation, SymbolKey typeId, out List<SymbolKey> dependentTypeIds) { dependentTypeIds = null; ConcurrentDictionary<SymbolKey, List<SymbolKey>> dictionary; return cache.TryGetValue(compilation, out dictionary) && dictionary.TryGetValue(typeId, out dependentTypeIds); }
public void Reachability () { var cwt = new ConditionalWeakTable <object,object> (); List<object> keepAlive; List<WeakReference> keys; FillStuff (cwt, out keepAlive, out keys); GC.Collect (); Assert.IsTrue (keys [0].IsAlive, "r0"); Assert.IsFalse (keys [1].IsAlive, "r1"); Assert.IsTrue (keys [2].IsAlive, "r2"); object res; Assert.IsTrue (cwt.TryGetValue (keepAlive [0], out res), "ka0"); Assert.IsTrue (res is Link, "ka1"); Link link = res as Link; Assert.IsTrue (cwt.TryGetValue (link.obj, out res), "ka2"); Assert.AreEqual ("str0", res, "ka3"); }
public void OldGenKeysMakeNewGenObjectsReachable () { if (GC.MaxGeneration == 0) /*Boehm doesn't handle ephemerons */ Assert.Ignore ("Not working on Boehm."); ConditionalWeakTable<object, Val> table = new ConditionalWeakTable<object, Val>(); List<Key> keys = new List<Key>(); // // This list references all keys for the duration of the program, so none // should be collected ever. // for (int x = 0; x < 1000; x++) keys.Add (new Key () { Foo = x }); for (int i = 0; i < 1000; ++i) { // Insert all keys into the ConditionalWeakTable foreach (var key in keys) table.Add (key, new Val () { Foo = key.Foo }); // Look up all keys to verify that they are still there Val val; foreach (var key in keys) Assert.IsTrue (table.TryGetValue (key, out val), "#1-" + i + "-k-" + key); // Remove all keys from the ConditionalWeakTable foreach (var key in keys) Assert.IsTrue (table.Remove (key), "#2-" + i + "-k-" + key); } }
public void TryGetValue () { var cwt = new ConditionalWeakTable <object,object> (); object res; object c = new Key (); cwt.Add (c, "foo"); try { cwt.TryGetValue (null, out res); Assert.Fail ("#0"); } catch (ArgumentNullException) {} Assert.IsFalse (cwt.TryGetValue ("foo", out res), "#1"); Assert.IsTrue (cwt.TryGetValue (c, out res), "#2"); Assert.AreEqual ("foo", res, "#3"); }
private static SemanticModel GetCachedSemanticModel( ConditionalWeakTable<SyntaxNode, WeakReference<SemanticModel>> nodeMap, SyntaxNode newMember) { SemanticModel model; WeakReference<SemanticModel> cached; if (!nodeMap.TryGetValue(newMember, out cached) || !cached.TryGetTarget(out model)) { return null; } return model; }
public void Reachability () { if (GC.MaxGeneration == 0) /*Boehm doesn't handle ephemerons */ Assert.Ignore ("Not working on Boehm."); var cwt = new ConditionalWeakTable <object,object> (); List<object> keepAlive = null; List<WeakReference> keys = null; Thread t = new Thread (delegate () { FillStuff (cwt, out keepAlive, out keys); }); t.Start (); t.Join (); GC.Collect (); Assert.IsTrue (keys [0].IsAlive, "r0"); Assert.IsFalse (keys [1].IsAlive, "r1"); Assert.IsTrue (keys [2].IsAlive, "r2"); object res; Assert.IsTrue (cwt.TryGetValue (keepAlive [0], out res), "ka0"); Assert.IsTrue (res is Link, "ka1"); Link link = res as Link; Assert.IsTrue (cwt.TryGetValue (link.obj, out res), "ka2"); Assert.AreEqual ("str0", res, "ka3"); }
private static ConditionalWeakTable<DocumentId, SyntaxTreeIndex> GetInfoTable( BranchId branchId, Workspace workspace, ConditionalWeakTable<BranchId, ConditionalWeakTable<DocumentId, SyntaxTreeIndex>> cache) { return cache.GetValue(branchId, id => { if (id == workspace.PrimaryBranchId) { workspace.DocumentClosed += (sender, e) => { if (!e.Document.IsFromPrimaryBranch()) { return; } if (cache.TryGetValue(e.Document.Project.Solution.BranchId, out var infoTable)) { // remove closed document from primary branch from live cache. infoTable.Remove(e.Document.Id); } }; } return new ConditionalWeakTable<DocumentId, SyntaxTreeIndex>(); }); }
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)); } }
// add the handler to the CWT - this keeps the handler alive throughout // the lifetime of the target, without prolonging the lifetime of // the target void AddHandlerToCWT(Delegate handler, ConditionalWeakTable<object, object> cwt) { object value; object target = handler.Target; if (target == null) target = StaticSource; if (!cwt.TryGetValue(target, out value)) { // 99% case - the target only listens once cwt.Add(target, handler); } else { // 1% case - the target listens multiple times // we store the delegates in a list List<Delegate> list = value as List<Delegate>; if (list == null) { // lazily allocate the list, and add the old handler Delegate oldHandler = value as Delegate; list = new List<Delegate>(); list.Add(oldHandler); // install the list as the CWT value cwt.Remove(target); cwt.Add(target, list); } // add the new handler to the list list.Add(handler); } }
public static void Clear_AllValuesRemoved(int numObjects) { var cwt = new ConditionalWeakTable<object, object>(); MethodInfo clear = cwt.GetType().GetMethod("Clear", BindingFlags.NonPublic | BindingFlags.Instance); if (clear == null) { // Couldn't access the Clear method; skip the test. return; } object[] keys = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray(); object[] values = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray(); for (int iter = 0; iter < 2; iter++) { // Add the objects for (int i = 0; i < numObjects; i++) { cwt.Add(keys[i], values[i]); Assert.Same(values[i], cwt.GetValue(keys[i], _ => new object())); } // Clear the table clear.Invoke(cwt, null); // Verify the objects are removed for (int i = 0; i < numObjects; i++) { object ignored; Assert.False(cwt.TryGetValue(keys[i], out ignored)); } // Do it a couple of times, to make sure the table is still usable after a clear. } }
public void PromotedCwtPointingToYoungStuff () { var cwt = new ConditionalWeakTable <object,object> (); var handles = FillTable3 (cwt); GC.Collect (0); /*Be 100% sure it will be on the young gen*/ /*cwt array now will be on old gen*/ ForceMinor (); ForceMinor (); ForceMinor (); //Make them non pinned MakeObjMovable (handles); GC.Collect (0); //Force a minor GC - this should cause ForceMinor (); ForceMinor (); ForceMinor (); ForceMinor (); GC.Collect (0); object r1, r2; Assert.IsTrue (cwt.TryGetValue (handles[0].Target, out r1), "#1"); Assert.IsTrue (cwt.TryGetValue (handles[1].Target, out r2), "#2"); GC.Collect (); cwt.GetHashCode (); }