From fc43c7e3d506aedd476cc472b9bdeb7a53b3aa44 Mon Sep 17 00:00:00 2001 From: Max Katz Date: Mon, 15 Jan 2024 23:10:57 -0800 Subject: [PATCH] Fix browser issue with dispatcher used before initialization --- .../Avalonia.Browser/BrowserAppBuilder.cs | 5 +++ .../BrowserSingleViewLifetime.cs | 36 ++++++++++--------- 2 files changed, 25 insertions(+), 16 deletions(-) diff --git a/src/Browser/Avalonia.Browser/BrowserAppBuilder.cs b/src/Browser/Avalonia.Browser/BrowserAppBuilder.cs index eaa72c1931..2cb69fc835 100644 --- a/src/Browser/Avalonia.Browser/BrowserAppBuilder.cs +++ b/src/Browser/Avalonia.Browser/BrowserAppBuilder.cs @@ -58,6 +58,7 @@ public static class BrowserAppBuilder .AfterSetup(_ => { lifetime.View = new AvaloniaView(mainDivId); + lifetime.CompleteSetup(); }) .SetupWithLifetime(lifetime); } @@ -77,6 +78,10 @@ public static class BrowserAppBuilder var lifetime = new BrowserSingleViewLifetime(); builder + .AfterSetup(_ => + { + lifetime.CompleteSetup(); + }) .SetupWithLifetime(lifetime); } diff --git a/src/Browser/Avalonia.Browser/BrowserSingleViewLifetime.cs b/src/Browser/Avalonia.Browser/BrowserSingleViewLifetime.cs index 6607bcf539..1cf0e31ba0 100644 --- a/src/Browser/Avalonia.Browser/BrowserSingleViewLifetime.cs +++ b/src/Browser/Avalonia.Browser/BrowserSingleViewLifetime.cs @@ -13,26 +13,18 @@ internal class BrowserSingleViewLifetime : ISingleViewApplicationLifetime, IActi { public BrowserSingleViewLifetime() { - bool? initiallyVisible = InputHelper.SubscribeVisibilityChange(visible => + _initiallyVisible = InputHelper.SubscribeVisibilityChange(visible => { - initiallyVisible = null; - (visible ? Activated : Deactivated)?.Invoke(this, new ActivatedEventArgs(ActivationKind.Background)); + _initiallyVisible = null; + var eventToTrigger = (visible ? Activated : Deactivated); + Dispatcher.UIThread.Invoke( + () => eventToTrigger?.Invoke(this, new ActivatedEventArgs(ActivationKind.Background)), + DispatcherPriority.Background); }); - - // Trigger Activated as an initial state, if web page is visible, and wasn't hidden during initialization. - if (initiallyVisible == true) - { - Dispatcher.UIThread.Invoke(() => - { - if (initiallyVisible == true) - { - Activated?.Invoke(this, new ActivatedEventArgs(ActivationKind.Background)); - } - }); - } } public AvaloniaView? View; + private bool? _initiallyVisible; public Control? MainView { @@ -61,5 +53,17 @@ internal class BrowserSingleViewLifetime : ISingleViewApplicationLifetime, IActi public event EventHandler? Deactivated; public bool TryLeaveBackground() => false; - public bool TryEnterBackground() => true; + public bool TryEnterBackground() => false; + + internal void CompleteSetup() + { + // Trigger Activated as an initial state, if web page is visible, and wasn't hidden during initialization. + Dispatcher.UIThread.Invoke(() => + { + if (_initiallyVisible == true) + { + Activated?.Invoke(this, new ActivatedEventArgs(ActivationKind.Background)); + } + }, DispatcherPriority.Background); + } }