Browse Source

Fix ClassicDesktop Lifetime so that ShutdownRequested event is raised even with programatic calls to Shutdown.

pull/7400/head
Dan Walmsley 5 years ago
parent
commit
eb6750822c
  1. 71
      src/Avalonia.Controls/ApplicationLifetimes/ClassicDesktopStyleApplicationLifetime.cs

71
src/Avalonia.Controls/ApplicationLifetimes/ClassicDesktopStyleApplicationLifetime.cs

@ -83,29 +83,9 @@ namespace Avalonia.Controls.ApplicationLifetimes
public void Shutdown(int exitCode = 0) public void Shutdown(int exitCode = 0)
{ {
if (_isShuttingDown) DoShutdown(new ShutdownRequestedEventArgs(), exitCode);
throw new InvalidOperationException("Application is already shutting down.");
_exitCode = exitCode;
_isShuttingDown = true;
try
{
foreach (var w in Windows)
w.Close();
var e = new ControlledApplicationLifetimeExitEventArgs(exitCode);
Exit?.Invoke(this, e);
_exitCode = e.ApplicationExitCode;
}
finally
{
_cts?.Cancel();
_cts = null;
_isShuttingDown = false;
}
} }
public int Start(string[] args) public int Start(string[] args)
{ {
Startup?.Invoke(this, new ControlledApplicationLifetimeStartupEventArgs(args)); Startup?.Invoke(this, new ControlledApplicationLifetimeStartupEventArgs(args));
@ -145,23 +125,52 @@ namespace Avalonia.Controls.ApplicationLifetimes
if (_activeLifetime == this) if (_activeLifetime == this)
_activeLifetime = null; _activeLifetime = null;
} }
private void OnShutdownRequested(object sender, ShutdownRequestedEventArgs e) private void DoShutdown(ShutdownRequestedEventArgs e, int exitCode = 0)
{ {
ShutdownRequested?.Invoke(this, e); ShutdownRequested?.Invoke(this, e);
if (e.Cancel) if (e.Cancel)
return; return;
// When an OS shutdown request is received, try to close all non-owned windows. Windows can cancel if (_isShuttingDown)
// shutdown by setting e.Cancel = true in the Closing event. Owned windows will be shutdown by their throw new InvalidOperationException("Application is already shutting down.");
// owners.
foreach (var w in Windows) _exitCode = exitCode;
if (w.Owner is null) _isShuttingDown = true;
w.Close();
if (Windows.Count > 0) try
e.Cancel = true; {
// When an OS shutdown request is received, try to close all non-owned windows. Windows can cancel
// shutdown by setting e.Cancel = true in the Closing event. Owned windows will be shutdown by their
// owners.
foreach (var w in Windows)
{
if (w.Owner is null)
{
w.Close();
}
}
if (Windows.Count > 0)
{
e.Cancel = true;
return;
}
var e = new ControlledApplicationLifetimeExitEventArgs(exitCode);
Exit?.Invoke(this, e);
_exitCode = e.ApplicationExitCode;
}
finally
{
_cts?.Cancel();
_cts = null;
_isShuttingDown = false;
}
} }
private void OnShutdownRequested(object sender, ShutdownRequestedEventArgs e) => DoShutdown(e);
} }
public class ClassicDesktopStyleApplicationLifetimeOptions public class ClassicDesktopStyleApplicationLifetimeOptions

Loading…
Cancel
Save