@@ -24,6 +24,8 @@ public sealed partial class MainWindow : Window
2424 private readonly LogManager _logManager ;
2525 private AppWindow _appWindow ;
2626 private bool _isRealExit = false ;
27+ private DispatcherTimer ? _refreshTimer ;
28+ private bool _isLoadServicesRunning = false ;
2729
2830 public ObservableCollection < Service > Services { get ; } = new ( ) ;
2931
@@ -61,11 +63,23 @@ public MainWindow()
6163 LoadServices ( ) ;
6264 Title = "ServicesApp" ;
6365
64- this . Closed += ( s , e ) => _serviceManager . Dispose ( ) ;
66+ this . Closed += OnWindowClosed ;
6567
66- var timer = new DispatcherTimer { Interval = TimeSpan . FromSeconds ( 2 ) } ;
67- timer . Tick += ( s , e ) => LoadServices ( true ) ;
68- timer . Start ( ) ;
68+ _refreshTimer = new DispatcherTimer { Interval = TimeSpan . FromSeconds ( 2 ) } ;
69+ _refreshTimer . Tick += ( s , e ) => LoadServices ( true ) ;
70+ _refreshTimer . Start ( ) ;
71+ }
72+
73+ private void OnWindowClosed ( object sender , WindowEventArgs args )
74+ {
75+ _refreshTimer ? . Stop ( ) ;
76+ _refreshTimer = null ;
77+ if ( _serviceManager != null )
78+ {
79+ _serviceManager . ServiceUpdated -= OnServiceUpdated ;
80+ _serviceManager . Dispose ( ) ;
81+ }
82+ TrayIcon ? . Dispose ( ) ;
6983 }
7084
7185 private void InitializeTrayIcon ( )
@@ -136,6 +150,7 @@ public void ShowWindow()
136150 _appWindow . Show ( ) ;
137151 _appWindow . MoveInZOrderAtTop ( ) ;
138152 this . Activate ( ) ;
153+ LoadServices ( ) ; // Refresh immediately when showing
139154 }
140155
141156 public void RealExit ( )
@@ -172,6 +187,12 @@ private void OnServiceUpdated(object? sender, Service service)
172187
173188 private async void LoadServices ( bool silent = false )
174189 {
190+ if ( _isLoadServicesRunning ) return ;
191+
192+ // Optimization: Do not refresh UI if window is hidden and this is an automated refresh
193+ if ( silent && _appWindow != null && ! _appWindow . IsVisible ) return ;
194+
195+ _isLoadServicesRunning = true ;
175196 try
176197 {
177198 if ( ! silent ) UpdateStatus ( "正在加载服务..." ) ;
@@ -205,6 +226,10 @@ private async void LoadServices(bool silent = false)
205226 {
206227 if ( ! silent ) UpdateStatus ( $ "加载服务失败: { ex . Message } ") ;
207228 }
229+ finally
230+ {
231+ _isLoadServicesRunning = false ;
232+ }
208233 }
209234
210235 private void OnRefreshClick ( object sender , RoutedEventArgs e )
0 commit comments