This question relates to restarting an application.
I have seen this question. However, the question, and as far as I have been able to tell, the answers, are almost a decade old, and none of them seem to provide an answer to this specific question ( of how to define second Application object once the first has had its .Shutdown
method called ).
Attempting to declare new App( )
after the first has had its .Shutdown( )
method called results in the following exception:
Is there anything that I can do with the original App
object to prevent his from happening?
In compliance with the Minimal, Complete and Verifiable Example requirements:
MAKE CERTAIN THAT App.xaml
HAS ITS BUILD ACTION SET TO Page
.
App.xaml.cs:
using System;
namespace MCVE {
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App {
private static bool _isRestarting = true;
public static bool IsRestarting {
get => _isRestarting;
set => _isRestarting = value;
}
[STAThread]
public static void Main( ) {
while ( IsRestarting ) {
IsRestarting = false;
App program = new App( );
program.InitializeComponent( );
program.Run( );
}
}
}
}
MainWindow.xaml:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Class="MCVE.MainWindow"
mc:Ignorable="d" Title="MainWindow" Height="450" Width="800">
<UniformGrid Rows="1">
<Button Content="Restart" Click="Restart" />
<Button Content="Exit" Click="Shutdown" />
</UniformGrid>
</Window>
MainWindow.Xaml.cs:
using System.Windows;
namespace MCVE {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow( ) {
InitializeComponent( );
}
private void Restart( object sender, RoutedEventArgs e ) {
App.IsRestarting = true;
Shutdown( sender, e );
}
private void Shutdown( object sender, RoutedEventArgs e ) =>
Application.Current?.Shutdown( );
}
}
To Reproduce: Click the button that says Restart
.