4

Whenever I try to restart Avalonia application form base application, I get an exception: "Setup was already called on one of AppBuilder instances." on SetupWithLifetime() call.

Application Startup code is:

       public static void Start()
        {
            lifeTime = new ClassicDesktopStyleApplicationLifetime()
            {
                ShutdownMode = ShutdownMode.OnLastWindowClose
            };

            BuildAvaloniaApp().SetupWithLifetime(lifeTime);

            lifeTime.Start(new[] { "" });
        }

        public static AppBuilder BuildAvaloniaApp()
            => AppBuilder.Configure<App>()
                .UsePlatformDetect()
                .LogToTrace()
                .UseReactiveUI();

Application shutdown code is:

        lifeTime.Shutdown();
        lifeTime.Dispose();

Here's a link to functional example code, which produces this error: https://pastebin.com/J1jqppPv Has anyone encountered such problem? Thank you

user15123902
  • 123
  • 4

1 Answers1

1

SetupWithLifetime calls Setup which can only be called once. A possible solution is to call SetupWithoutStarting on BuildAvaloniaApp, which can only be called once as well, for example:

private static AppBuilder s_builder;

static void Main(string[] args)
{
    s_builder = BuildAvaloniaApp();
}

public static void Start()
{
    lifeTime = new ClassicDesktopStyleApplicationLifetime()
    {
        ShutdownMode = ShutdownMode.OnLastWindowClose
    };

    s_builder.Instance.Lifetime = lifeTime;
    s_builder.Instance.OnFrameworkInitializationCompleted();

    lifeTime.Start(new[] { "" });
}

private static AppBuilder BuildAvaloniaApp()
    => AppBuilder.Configure<App>()
        .UsePlatformDetect()
        .LogToTrace()
        .UseReactiveUI();

Additional note: Restarting the app probably won't work on macOS.

José Pedro
  • 1,097
  • 3
  • 14
  • 24
  • Thanks @José I need to start Avalonia app in separate thread to not block main application thread (therefore uses my example code starting threads). In this situation, I'm gettin 'Call from invalid thread' in OnFrameworkInitializationCompleted(). My workaround is not to stop lifetime, but only close MainWindow, and then show it again. Here is my code: https://pastebin.com/wMYaZFNp – user15123902 Feb 04 '21 at 09:16
  • That's one more problem with macOS (no idea if it's a target platform for you): https://github.com/AvaloniaUI/Avalonia/issues/2800. Running apps on different threads is also not easy (or even impossible), for example the UI thread is static: https://github.com/AvaloniaUI/Avalonia/blob/1a39210febf92e9e87b3ebacca9b56d99e660913/src/Avalonia.Base/Threading/Dispatcher.cs#L21. – José Pedro Feb 05 '21 at 15:57
  • My target platform is Linux, so the behaviour may be similar to MacOS. The solution, which I used and posted above is more like soft-restart :) Thanks a lot @José – user15123902 Feb 26 '21 at 13:51