From c56fc3f798df56963f13d3fd59bf4517c29576ea Mon Sep 17 00:00:00 2001 From: Nathan Nguyen Date: Fri, 31 Jul 2026 02:32:06 +1000 Subject: [PATCH] Fix Loaded event processing after a handler throws (#21877) * test: add failing test for Loaded processing after handler exception A control whose Loaded handler throws currently breaks the static loaded-processing machinery: remaining controls in the same dispatcher batch are skipped and, because _isLoadedProcessing is never reset, every control created afterwards app-wide never receives Loaded. The test attaches a throwing control between two siblings, expects the exception to surface from the dispatcher job, and asserts that both siblings and a control added in a later batch still get Loaded. Issue #18742 * fix: recover Loaded event processing after a handler throws Previously the static loadedProcessingAction iterated the pending controls with no exception handling. If any control's Loaded handler or OnLoaded override threw, the batch loop aborted, so: - _isLoadedProcessing stayed true forever, and since ScheduleOnLoadedCore only posts a dispatcher job when that flag is false, no control created afterwards, app-wide, ever received Loaded; - the remaining controls in the current batch were skipped; - the stuck processing queue retained control references (leak). The invariant violated was that _isLoadedProcessing is true only while a loaded-processing dispatcher job is actually scheduled or running. Fix: process the snapshot as a drain queue (Dequeue before invoking, because OnLoadedCore must not run twice for a control) and restore the invariant in a finally block: requeue the unprocessed remainder, clear the processing queue, reset the flag and post a new dispatcher job if work remains. try/finally was chosen over catching per control so the exception still propagates to the dispatcher as an unhandled exception (matching WPF semantics) instead of being swallowed or aggregated, while controls after the faulty one get Loaded on the next dispatcher job. Fixes #18742 --- src/Avalonia.Controls/Control.cs | 39 ++++++----- .../LoadedTests.cs | 67 ++++++++++++++++++- 2 files changed, 90 insertions(+), 16 deletions(-) diff --git a/src/Avalonia.Controls/Control.cs b/src/Avalonia.Controls/Control.cs index 6b37e48c42..4a17b69c81 100644 --- a/src/Avalonia.Controls/Control.cs +++ b/src/Avalonia.Controls/Control.cs @@ -93,7 +93,7 @@ namespace Avalonia.Controls private static bool _isLoadedProcessing = false; private static readonly HashSet _loadedQueue = new HashSet(); - private static readonly HashSet _loadedProcessingQueue = new HashSet(); + private static readonly Queue _loadedProcessingQueue = new Queue(); private LoadState _loadState = LoadState.Unloaded; private DataTemplates? _dataTemplates; @@ -244,29 +244,38 @@ namespace Avalonia.Controls { // Copy the loaded queue for processing // There was a possibility of the "Collection was modified; enumeration operation may not execute." - // exception when only a single hash set was used. This could happen when new controls are added - // within the Loaded callback/event itself. To fix this, two hash sets are used and while one is + // exception when only a single collection was used. This could happen when new controls are added + // within the Loaded callback/event itself. To fix this, two collections are used and while one is // being processed the other accepts adding new controls to process next. - _loadedProcessingQueue.Clear(); foreach (Control control in _loadedQueue) { - _loadedProcessingQueue.Add(control); + _loadedProcessingQueue.Enqueue(control); } _loadedQueue.Clear(); - foreach (Control control in _loadedProcessingQueue) + try { - control.OnLoadedCore(); + while (_loadedProcessingQueue.Count > 0) + { + _loadedProcessingQueue.Dequeue().OnLoadedCore(); + } } - - _loadedProcessingQueue.Clear(); - _isLoadedProcessing = false; - - // Restart if any controls were added to the queue while processing - if (_loadedQueue.Count > 0) + finally { - _isLoadedProcessing = true; - Dispatcher.UIThread.Post(loadedProcessingAction!, DispatcherPriority.Loaded); + // An exception from OnLoadedCore (a Loaded handler or override) propagates to the + // dispatcher as usual, but the processing machinery must recover: controls left + // unprocessed are requeued and a new dispatcher job is posted for them, so a single + // faulty handler cannot stop Loaded from ever being raised again (see #18742). + _loadedQueue.UnionWith(_loadedProcessingQueue); + _loadedProcessingQueue.Clear(); + _isLoadedProcessing = false; + + // Restart if any controls were added to the queue while processing + if (_loadedQueue.Count > 0) + { + _isLoadedProcessing = true; + Dispatcher.UIThread.Post(loadedProcessingAction!, DispatcherPriority.Loaded); + } } }; diff --git a/tests/Avalonia.Controls.UnitTests/LoadedTests.cs b/tests/Avalonia.Controls.UnitTests/LoadedTests.cs index fd70a0ed63..402b5be246 100644 --- a/tests/Avalonia.Controls.UnitTests/LoadedTests.cs +++ b/tests/Avalonia.Controls.UnitTests/LoadedTests.cs @@ -1,4 +1,5 @@ -using Avalonia.Platform; +using System; +using Avalonia.Platform; using Avalonia.Threading; using Avalonia.UnitTests; using Moq; @@ -73,6 +74,70 @@ public class LoadedTests : ScopedTestBase } } + [Fact] + public void Loaded_Exception_Does_Not_Prevent_Other_Controls_From_Loading() + { + // Some other tests are populating the queue and are not resetting the dispatcher, so we need to purge it + Control.ResetLoadedQueueForUnitTests(); + using (UnitTestApplication.Start(TestServices.StyledWindow)) + { + var window = new Window(); + window.Show(); + Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded, TestContext.Current.CancellationToken); + + // Batch 1: a control whose Loaded handler throws, plus siblings queued in the same batch. + var throwing = new Button(); + throwing.Loaded += (_, _) => throw new InvalidOperationException("Loaded handler failure"); + + var sibling1 = new Button(); + var sibling2 = new Button(); + int sibling1LoadedCount = 0, sibling2LoadedCount = 0; + sibling1.Loaded += (_, _) => sibling1LoadedCount++; + sibling2.Loaded += (_, _) => sibling2LoadedCount++; + + window.Content = new StackPanel { Children = { sibling1, throwing, sibling2 } }; + + // The exception must surface (propagate to the dispatcher), not be swallowed. + PumpLoadedJobs(swallowedExceptionsAllowed: 1); + + // Both siblings from the same batch must still have been loaded. + Assert.True(sibling1.IsLoaded); + Assert.True(sibling2.IsLoaded); + Assert.Equal(1, sibling1LoadedCount); + Assert.Equal(1, sibling2LoadedCount); + + // Batch 2: controls loaded afterwards must still receive Loaded. + var later = new Button(); + int laterLoadedCount = 0; + later.Loaded += (_, _) => laterLoadedCount++; + ((StackPanel)window.Content!).Children.Add(later); + + PumpLoadedJobs(swallowedExceptionsAllowed: 0); + + Assert.True(later.IsLoaded); + Assert.Equal(1, laterLoadedCount); + } + } + + private static void PumpLoadedJobs(int swallowedExceptionsAllowed) + { + // A throwing Loaded handler propagates its exception out of the dispatcher job. + // Keep pumping so that any rescheduled loaded-processing jobs also run, but fail + // if more exceptions escape than the single expected one. + for (var i = 0; i <= swallowedExceptionsAllowed; i++) + { + try + { + Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded, TestContext.Current.CancellationToken); + return; + } + catch (InvalidOperationException) when (i < swallowedExceptionsAllowed) + { + // Expected exception from the throwing Loaded handler; continue pumping. + } + } + } + [Fact] public void Loaded_Should_Not_Be_Raised_If_Detached_From_Visual_Tree() {