From 24c5519e7199f9b7631c25d7b75876ee69669aec Mon Sep 17 00:00:00 2001 From: Dariusz Komosinski Date: Sat, 7 Dec 2019 18:31:19 +0100 Subject: [PATCH] Use CondtionalWeakTable to avoid FocusManager becoming a GC root for all focus scopes. --- src/Avalonia.Input/FocusManager.cs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/Avalonia.Input/FocusManager.cs b/src/Avalonia.Input/FocusManager.cs index 77902a7390..a9ce8ee494 100644 --- a/src/Avalonia.Input/FocusManager.cs +++ b/src/Avalonia.Input/FocusManager.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.CompilerServices; using Avalonia.Interactivity; using Avalonia.VisualTree; @@ -17,8 +18,8 @@ namespace Avalonia.Input /// /// The focus scopes in which the focus is currently defined. /// - private readonly Dictionary _focusScopes = - new Dictionary(); + private readonly ConditionalWeakTable _focusScopes = + new ConditionalWeakTable(); /// /// Initializes a new instance of the class. @@ -110,7 +111,18 @@ namespace Avalonia.Input { Contract.Requires(scope != null); - _focusScopes[scope] = element; + if (_focusScopes.TryGetValue(scope, out IInputElement existingElement)) + { + if (element != existingElement) + { + _focusScopes.Remove(scope); + _focusScopes.Add(scope, element); + } + } + else + { + _focusScopes.Add(scope, element); + } if (Scope == scope) {