Files
zijiuqizonghejianyanyi/AppShutdownCoordinator.cs

66 lines
1.8 KiB
C#
Raw Permalink Normal View History

2026-03-16 19:10:33 +08:00
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
namespace
{
internal static class AppShutdownCoordinator
{
private static int _shutdownRequested;
public static bool IsShutdownInProgress
{
get
{
Application application = Application.Current;
if (application == null)
{
return Interlocked.CompareExchange(ref _shutdownRequested, 0, 0) == 1;
}
return Interlocked.CompareExchange(ref _shutdownRequested, 0, 0) == 1
|| application.Dispatcher.HasShutdownStarted
|| application.Dispatcher.HasShutdownFinished;
}
}
public static void RequestShutdown()
{
Application application = Application.Current;
if (application == null)
{
return;
}
if (Interlocked.Exchange(ref _shutdownRequested, 1) == 1)
{
return;
}
application.Dispatcher.BeginInvoke(
DispatcherPriority.ApplicationIdle,
new Action(() =>
{
if (application.Dispatcher.HasShutdownStarted || application.Dispatcher.HasShutdownFinished)
{
return;
}
application.Shutdown();
}));
}
public static bool ShouldSuppressDuringShutdown(Exception exception)
{
if (!IsShutdownInProgress || exception == null)
{
return false;
}
return exception is InvalidOperationException || exception is Win32Exception;
}
}
}