public void ClearCompilationScopeMap(Compilation compilation) { lock (_gate) { _lazyCompilationScopeCache?.Remove(compilation); } }
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 void ClearValue() { var microThread = Scheduler.CurrentMicroThread; lock (values) { if (microThread == null) { valueOutOfMicrothread = default(T); valueOutOfMicrothreadSet = false; } else { values.Remove(microThread); } } }
public static void Concurrent_GetValue_Read_Remove_SameObject() { object key = new object(); object value = new object(); var cwt = new ConditionalWeakTable <object, object>(); DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(0.25); Parallel.For(0, Environment.ProcessorCount, i => { while (DateTime.UtcNow < end) { Assert.Same(value, cwt.GetValue(key, _ => value)); cwt.Remove(key); } }); }
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 async Task <IEnumerable <CompletionItem> > GetItemsWorkerAsync(Document document, int position, CompletionTriggerInfo triggerInfo, 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 <AbstractSyntaxContext> 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); var options = GetOptions(document, triggerInfo, context); if (!relatedDocumentIds.Any()) { IEnumerable <ISymbol> itemsForCurrentDocument = await GetSymbolsWorker(position, preselect, context, options, cancellationToken).ConfigureAwait(false); itemsForCurrentDocument = itemsForCurrentDocument ?? SpecializedCollections.EmptyEnumerable <ISymbol>(); return(await CreateItemsAsync(position, itemsForCurrentDocument, context, null, null, preselect, cancellationToken).ConfigureAwait(false)); } var contextAndSymbolLists = await GetPerContextSymbols(document, position, options, new[] { document.Id }.Concat(relatedDocumentIds), preselect, cancellationToken).ConfigureAwait(false); Dictionary <ISymbol, AbstractSyntaxContext> orignatingContextMap = null; var unionedSymbolsList = UnionSymbols(contextAndSymbolLists, out orignatingContextMap); var missingSymbolsMap = FindSymbolsMissingInLinkedContexts(unionedSymbolsList, contextAndSymbolLists); var totalProjects = contextAndSymbolLists.Select(t => t.Item1.ProjectId).ToList(); var textChangeSpan = await GetTextChangeSpanAsync(position, context, cancellationToken).ConfigureAwait(false); return(CreateItems(position, unionedSymbolsList, textChangeSpan, orignatingContextMap, missingSymbolsMap, totalProjects, preselect: preselect, cancellationToken: cancellationToken)); }
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); } } }
public override async Task Invoke(IOwinContext context) { bool bodyIsJson = context.Request.ContentType?.Contains(ContentType.Json) ?? false; if (bodyIsJson && (context.Request.Method == Http.POST || context.Request.Method == Http.PUT)) { var json = await Common.Utils.CommonUtils.GetRequestBodyFromRequestStream(context.Request); var body = JToken.Parse(json); RequestJsonBody.Add(context.Request, body); } await Next.Invoke(context); if (bodyIsJson) { RequestJsonBody.Remove(context.Request); } }
private async Task <HostSessionStartAnalysisScope> GetSessionAnalysisScopeAsync( DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { try { return(await GetSessionAnalysisScopeCoreAsync(analyzer, analyzerExecutor).ConfigureAwait(false)); } catch (OperationCanceledException) { // Task to compute the scope was cancelled. // Clear the entry in scope map for analyzer, so we can attempt a retry. _sessionScopeMap.Remove(analyzer); analyzerExecutor.CancellationToken.ThrowIfCancellationRequested(); return(await GetSessionAnalysisScopeAsync(analyzer, analyzerExecutor).ConfigureAwait(false)); } }
private ITemplateProvider FindTemplateProvider([NotNull] object item, DependencyObject container) { var usedProvidersForItem = usedProviders.GetOrCreateValue(item); var shouldClear = true; WeakReference lastContainer; // We check if this item has been templated recently. if (lastContainers.TryGetValue(item, out lastContainer) && lastContainer.IsAlive) { // If so, check if the last container used is a parent of the container to use now. var parent = VisualTreeHelper.GetParent(container); while (parent != null) { // If so, we are applying template recursively. We want don't want to use the same template // provider that the previous time, so we don't clear the list of providers already used. if (Equals(lastContainer.Target, parent)) { shouldClear = false; break; } parent = VisualTreeHelper.GetParent(parent); } } // In any other case, we clear the list of used providers. if (shouldClear) { usedProvidersForItem.Clear(); } lastContainers.Remove(item); var availableSelectors = templateProviders.Where(x => x.Match(item)).ToList(); var result = availableSelectors.FirstOrDefault(x => !usedProvidersForItem.Contains(x.Name)); if (result != null) { usedProvidersForItem.Add(result.Name); lastContainers.Add(item, new WeakReference(container)); } return(result); }
private static async Task <ImmutableArray <SearchResult> > TryFilterPreviousSearchResultsAsync( Project project, Document searchDocument, string pattern, PatternMatcher nameMatcher, PatternMatcher containerMatcherOpt, ArrayBuilder <PatternMatch> nameMatches, ArrayBuilder <PatternMatch> containerMatches, CancellationToken cancellationToken) { // Searching an entire project. See if we already performed that same // search with a substring of the current pattern. if so, we can use // the previous result and just filter that down. This is useful for // the common case where a user types some pattern, then keeps adding // to it. ImmutableArray <SearchResult> searchResults; if (s_lastProjectSearchCache.TryGetValue(project, out var previousResult) && pattern.StartsWith(previousResult.Item1)) { // We can reuse the previous results and just filter them. searchResults = FilterPreviousResults( previousResult.Item2, nameMatcher, containerMatcherOpt, nameMatches, containerMatches, cancellationToken); } else { // Didn't have previous results. Or it was a very different pattern. // Can't reuse. searchResults = await ComputeSearchResultsAsync( project, searchDocument, nameMatcher, containerMatcherOpt, nameMatches, containerMatches, cancellationToken).ConfigureAwait(false); } // Would like to use CWT.AddOrUpdate. But that is not available on the // version of .Net that we're using. So we need to take lock as we're // making multiple mutations. lock (s_lastProjectSearchCache) { s_lastProjectSearchCache.Remove(project); s_lastProjectSearchCache.Add(project, Tuple.Create(pattern, searchResults)); } return(searchResults); }
void IWpfTextViewConnectionListener.SubjectBuffersDisconnected(IWpfTextView textView, ConnectionReason reason, Collection <ITextBuffer> subjectBuffers) { lock (s_gate) { // we need to check all buffers reported since we will be called after actual changes have happened. // for example, if content type of a buffer changed, we will be called after it is changed, rather than before it. foreach (var buffer in subjectBuffers) { if (s_map.TryGetValue(buffer, out var set)) { set.Remove(textView); if (set.Count == 0) { s_map.Remove(buffer); } } } } }
private void OnDocumentOrProjectAnalyzed(Guid documentOrProjectGuid, Project project) { if (!project.SupportsCompilation) { return; } var currentTime = DateTime.UtcNow; var projectAnalysisState = _projectAnalysisStateCache.GetValue(project, CreateProjectAnalysisState); projectAnalysisState.PendingDocumentsOrProject.Remove(documentOrProjectGuid); projectAnalysisState.LastAccessTime = currentTime; if (projectAnalysisState.PendingDocumentsOrProject.Count == 0) { // PERF: We have computed and cached all documents and project diagnostics for the given project, so drop the CompilationWithAnalyzers instance that also caches all these diagnostics. _projectAnalysisStateCache.Remove(project); _hostAnalyzerManager.DisposeCompilationWithAnalyzers(project); } var minutesSinceCleanup = (currentTime - _lastCacheCleanupTime).TotalMinutes; if (minutesSinceCleanup >= cacheCleanupIntervalInMinutes) { // PERF: For projects which haven't been analyzed recently, drop the CompilationWithAnalyzers instance to reduce memory pressure. // Subsequent diagnostic request with instantiate a new CompilationWithAnalyzers for these projects. foreach (var p in project.Solution.Projects) { ProjectAnalysisState state; if (_projectAnalysisStateCache.TryGetValue(p, out state)) { var timeSinceLastAccess = currentTime - state.LastAccessTime; if (timeSinceLastAccess.TotalMinutes >= cacheCleanupIntervalInMinutes) { _hostAnalyzerManager.DisposeCompilationWithAnalyzers(p); state.LastAccessTime = currentTime; } } } _lastCacheCleanupTime = currentTime; } }
private static void OnWindowActivated(object sender, WindowActivatedEventArgs e) { var window = (Window)sender; window.Activated -= OnWindowActivated; if (_commandManagerPerWindow.TryGetValue(window, out var commandManager)) { _commandManagerPerWindow.Remove(window); Log.Debug($"Window '{window.GetType().Name}' has been activated, retrying the keyboard subscriptions"); SubscribeToKeyboardEvents(commandManager, window); } else { Log.Error($"Window '{window.GetType().Name}' has been activated, but could not find an ICommandManager registration in the temporary dictionary"); } }
private async Task ResponseReceivedHandler(object sender, ResponseReceivedEventArgs e) { try { var sw = Stopwatch.StartNew(); if (MessageReceived != null) { await MessageReceived.InvokeAsync(this, new MessageEventArgs(e.Message)).ConfigureAwait(false); } if (e.Message?.Body is null) { return; } var body = e.Message.Body.GetValue(); if (EnableCompleteMessageCache) { ResponseMessageCache.Add(body, e.Message); } Status.IncrementCurrentMessagesBeingProcessed(); try { await Processor.ProcessAsync(body, _cTokenSource.Token).ConfigureAwait(false); } catch (Exception ex) { Core.Log.Write(ex); Status.IncrementTotalExceptions(); } sw.Stop(); Status.ReportProcessingTime(sw.Elapsed.TotalMilliseconds); Status.DecrementCurrentMessagesBeingProcessed(); Status.IncrementTotalMessagesProccesed(); if (EnableCompleteMessageCache) { ResponseMessageCache.Remove(body); } } catch (Exception ex) { Core.Log.Write(ex); Status.IncrementTotalExceptions(); } }
public static void ShowOn(ICharacter character, string message) { if (!ClientChatDisclaimerConfirmationHelper.IsChatAllowedForCurrentServer || ClientChatDisclaimerConfirmationHelper.IsNeedToDisplayDisclaimerForCurrentServer) { return; } message = message.ToLowerInvariant(); var positionOffset = (0, character.ProtoCharacter.CharacterWorldHeight + 0.25); if (DisplayedMessages.TryGetValue(character, out var control)) { DisplayedMessages.Remove(character); if (control.isLoaded) { // destroy already displayed message control control.Hide(fast: true); ClientTimersSystem.AddAction( 0.075, () => ShowOn(character, message)); return; } } // create and setup new message control control = new CharacterLocalChatMessageDisplay(); control.Setup(message); control.attachedComponent = Api.Client.UI.AttachControl( character, control, positionOffset: positionOffset, isScaleWithCameraZoom: false, isFocusable: false); ClientTimersSystem.AddAction(TimeoutSeconds, () => control.Hide(fast: false)); DisplayedMessages.Add(character, control); }
public void Dispose(object handle) { if (handle == null) { return; } Operation(handle: handle, cancel_op: (internal_fsw, fsw) => { if (internal_fsw != null) { internal_fsw.Dispose(); } var inner_key = internal_map [handle]; internal_map.Remove(handle); external_map.Remove(handle); event_map.Remove(inner_key); handle = null; }); }
/// <summary> /// Clears all attached properties in the specified item. /// </summary> protected override bool ClearInternal(object item) { #if !WINFORMS && !PCL_WINRT && !PCL_Silverlight && !ANDROID && !TOUCH && !XAMARIN_FORMS var dependencyObject = item as DependencyObject; if (dependencyObject != null) { dependencyObject.ClearValue(AttachedValueDictionaryProperty); return(true); } #endif #if XAMARIN_FORMS var bindableObject = item as BindableObject; if (bindableObject != null) { bindableObject.ClearValue(AttachedValueDictionaryProperty); return(true); } #endif return(_internalDictionary.Remove(item)); }
public static void ClearCurrentData(ContextKey contextKey, bool removeContextData) { // Get the current ambient CallContext. ContextKey key = s_currentTransaction.Value; if (contextKey != null || key != null) { // removeContextData flag is used for perf optimization to avoid removing from the table in certain nested TransactionScope usage. if (removeContextData) { // if context key is passed in remove that from the contextDataTable, otherwise remove the default context key. s_contextDataTable.Remove(contextKey ?? key); } if (key != null) { s_currentTransaction.Value = null; } } }
public static bool PrefixUpdateMassFromInventories(List <MyCubeBlock> blocks, MyPhysicsBody rb, MyGridShape __instance) { RefTimeSpan time; if (!lastUpdateTimestamp.TryGetValue(__instance, out time)) { lastUpdateTimestamp.Add(__instance, new RefTimeSpan(MySession.Static.ElapsedGameTime)); return(true); } if ((MySession.Static.ElapsedGameTime - time.timespan).TotalMilliseconds < 1000) { return(false); } lastUpdateTimestamp.Remove(__instance); lastUpdateTimestamp.Add(__instance, new RefTimeSpan(MySession.Static.ElapsedGameTime)); return(true); }
public static void GetEnumerator_AddedAndRemovedItems_AppropriatelyShowUpInEnumeration() { var cwt = new ConditionalWeakTable <object, object>(); var enumerable = (IEnumerable <KeyValuePair <object, object> >)cwt; object key1 = new object(), value1 = new object(); for (int i = 0; i < 20; i++) // adding and removing multiple times, across internal container boundary { cwt.Add(key1, value1); Assert.Equal(1, enumerable.Count()); Assert.Equal(new KeyValuePair <object, object>(key1, value1), enumerable.First()); Assert.True(cwt.Remove(key1)); Assert.Equal(0, enumerable.Count()); } GC.KeepAlive(key1); GC.KeepAlive(value1); }
public static string GetTestAdapters(Project project) { var nugetsFolders = PackageManagementServices.ProjectOperations.GetInstalledPackages(project).Select(p => p.InstallPath); lock (projectTestAdapterListCache) { if (projectTestAdapterListCache.TryGetValue(project, out var cachePackages)) { if (cachePackages.Item1.SetEquals(nugetsFolders)) { return(cachePackages.Item2); } } var result = string.Empty; foreach (var folder in nugetsFolders) { if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) { continue; } foreach (var path in Directory.GetFiles(folder, "*.TestAdapter.dll", SearchOption.AllDirectories)) { result += path + ";"; } foreach (var path in Directory.GetFiles(folder, "*.testadapter.dll", SearchOption.AllDirectories)) { if (!result.Contains(path)) { result += path + ";"; } } } if (result.Length > 0) { result = result.Remove(result.Length - 1); } projectTestAdapterListCache.Remove(project); projectTestAdapterListCache.Add(project, new Tuple <HashSet <string>, string> (new HashSet <string> (nugetsFolders), result)); return(result); } }
// The method first adds some keys to the table // Then removes a key, checks that it was removed, adds the same key and verifies that it was added. public void AddRemoveKeyValPair(K[] keys, V[] values, int index, int repeat) { ConditionalWeakTable <K, V> tbl = new ConditionalWeakTable <K, V>(); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } for (int i = 0; i < repeat; i++) { // remove existing key and ensure method return true Test.Eval(tbl.Remove(keys[index]), "Err_013 Expected Remove to return true"); V val; // since we removed the key, TryGetValue should return false Test.Eval(!tbl.TryGetValue(keys[index], out val), "Err_014 Expected TryGetValue to return false"); Test.Eval(val == null, "Err_015 Expected val to be null"); // next add the same key tbl.Add(keys[index], values[index]); // since we added the key, TryGetValue should return true Test.Eval(tbl.TryGetValue(keys[index], out val), "Err_016 Expected TryGetValue to return true"); if (val == null && values[i] == null) { Test.Eval(true); } else if (val != null && values[index] != null && val.Equals(values[index])) { Test.Eval(true); } else { // only one of the values is null or the values don't match Test.Eval(false, "Err_017 The value returned by TryGetValue doesn't match the expected value"); } } }
public void ForgetTrackedObject(T old, T replacement = null) { LeakTracker tracker; if (leakTrackers.TryGetValue(old, out tracker)) { tracker.Dispose(); leakTrackers.Remove(old); } else { var trace = CaptureStackTrace(); Debug.WriteLine($"TRACEOBJECTPOOLLEAKS_BEGIN\nObject of type {typeof(T)} was freed, but was not from pool. \n Callstack: \n {trace} TRACEOBJECTPOOLLEAKS_END"); } if (replacement != null) { tracker = new LeakTracker(); leakTrackers.Add(replacement, tracker); } }
internal static void DisableBlur(Window win) { // アクリル効果を解除する SetBlur(win, AcrylicAccentState.Disabled); if (_internalStateTable.TryGetValue(win, out var internalState)) { var windowHelper = new WindowInteropHelper(win); var source = HwndSource.FromHwnd(windowHelper.Handle); source.RemoveHook(WndProc); // コマンド解除 win.CommandBindings.Remove(internalState.CloseCommand); win.CommandBindings.Remove(internalState.MinimizeCommand); win.CommandBindings.Remove(internalState.MaximizeCommand); win.CommandBindings.Remove(internalState.RestoreCommand); _internalStateTable.Remove(win); } }
internal static void RemoveMemberChangeAction(MemberChangeAction sub) { if (objectSubs.TryGetValue(sub.Target, out var subs)) { if (subs.TryGetValue(sub.Member, out var memberActions)) { // Debug.WriteLine ("REMOVE CHANGE ACTION " + sub.Target + " " + sub.Member); memberActions.RemoveAction(sub); if (memberActions.Count == 0) { subs.Remove(sub.Member); } } if (subs.Count == 0) { objectSubs.Remove(sub.Target); } } }
// 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]); } }
private static void OnIsAutoScrollEnabledPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ListViewBase @this = (ListViewBase)d; INotifyCollectionChanged? oldValue = (INotifyCollectionChanged?)e.OldValue, newValue = (INotifyCollectionChanged?)e.NewValue; // Remove the old handler, if necessary if (!(oldValue is null)) { ControlsMap.Remove(oldValue); oldValue.CollectionChanged -= INotifyCollectionChanged_CollectionChanged; } // Register the new collection, if needed if (!(newValue is null)) { ControlsMap.Add(newValue, @this); newValue.CollectionChanged += INotifyCollectionChanged_CollectionChanged; } }
// 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 AddRemove_DropValue() { var key = new object(); var value = new object(); var cwt = new ConditionalWeakTable <object, object>(); cwt.Add(key, value); cwt.Remove(key); // Verify that the removed entry is not keeping the value alive var wrValue = new WeakReference(value); value = null; GC.Collect(); Assert.False(wrValue.IsAlive); GC.KeepAlive(cwt); GC.KeepAlive(key); }
public async Task <SerializableDiagnosticAnalysisResults> GetDiagnosticsAsync( IEnumerable <string> analyzerIds, bool reportSuppressedDiagnostics, bool logPerformanceInfo, bool getTelemetryInfo, CancellationToken cancellationToken) { var(compilationWithAnalyzers, analyzerToIdMap) = await GetOrCreateCompilationWithAnalyzersAsync( _project, isDocumentAnalysis : _document != null, cancellationToken).ConfigureAwait(false); var analyzers = GetAnalyzers(analyzerToIdMap, analyzerIds); if (analyzers.IsEmpty) { return(SerializableDiagnosticAnalysisResults.Empty); } if (_document == null && analyzers.Length < compilationWithAnalyzers.Analyzers.Length) { // PERF: Generate a new CompilationWithAnalyzers with trimmed analyzers for non-document analysis case. compilationWithAnalyzers = compilationWithAnalyzers.Compilation.WithAnalyzers(analyzers, compilationWithAnalyzers.AnalysisOptions); } var cacheService = _project.Solution.Workspace.Services.GetRequiredService <IProjectCacheService>(); using var cache = cacheService.EnableCaching(_project.Id); var skippedAnalyzersInfo = _project.GetSkippedAnalyzersInfo(_analyzerInfoCache); try { return(await AnalyzeAsync(compilationWithAnalyzers, analyzerToIdMap, analyzers, skippedAnalyzersInfo, reportSuppressedDiagnostics, logPerformanceInfo, getTelemetryInfo, cancellationToken).ConfigureAwait(false)); } catch { // Do not re-use cached CompilationWithAnalyzers instance in presence of an exception, as the underlying analysis state might be corrupt. s_compilationWithAnalyzersCache.Remove(_project); throw; } }
internal static Type GetClassForInterface <T>() where T : IAttribute { var attClass = typeof(T); Type clazz; // LUCENENET: If the weakreference is dead, we need to explicitly update its key. // We synchronize on attClassImplMapLock to make the operation atomic. lock (attClassImplMapLock) { if (!attClassImplMap.TryGetValue(attClass, out var @ref) || [email protected](out clazz)) { #if FEATURE_CONDITIONALWEAKTABLE_ADDORUPDATE attClassImplMap.AddOrUpdate(attClass, CreateAttributeWeakReference(attClass, out clazz)); #else attClassImplMap.Remove(attClass); attClassImplMap.Add(attClass, CreateAttributeWeakReference(attClass, out clazz)); #endif } } return(clazz); }
public static void AddRemove_DropValue() { var key = new object(); var value = new object(); var cwt = new ConditionalWeakTable<object, object>(); cwt.Add(key, value); cwt.Remove(key); // Verify that the removed entry is not keeping the value alive var wrValue = new WeakReference(value); value = null; GC.Collect(); Assert.False(wrValue.IsAlive); GC.KeepAlive(cwt); GC.KeepAlive(key); }
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)); } }
public static void Concurrent_GetValue_Read_Remove_SameObject() { object key = new object(); object value = new object(); var cwt = new ConditionalWeakTable<object, object>(); DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(0.25); Parallel.For(0, Environment.ProcessorCount, i => { while (DateTime.UtcNow < end) { Assert.Same(value, cwt.GetValue(key, _ => value)); cwt.Remove(key); } }); }
// 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 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 Remove () { var cwt = new ConditionalWeakTable <object,object> (); object c = new Key (); cwt.Add (c, "x"); try { cwt.Remove (null); Assert.Fail ("#0"); } catch (ArgumentNullException) {} Assert.IsFalse (cwt.Remove ("x"), "#1"); Assert.IsTrue (cwt.Remove (c), "#2"); Assert.IsFalse (cwt.Remove (c), "#3"); }