@@ -43,23 +43,50 @@ public async Task StartAsync(CancellationToken cancellationToken)
4343 public async Task StopAsync ( CancellationToken cancellationToken )
4444 {
4545 logger . LogInformation ( "Application Stopping event raised!" ) ;
46- if ( player . Status . StillPlaying )
46+ try
4747 {
48- logger . LogInformation ( "Still playing music...saving current song and queue" ) ;
49- var lastState = new LastState
48+ if ( player . Status . StillPlaying )
5049 {
51- CurrentSong = player . Status . CurrentSong ,
52- Queue = player . SongQueue
53- } ;
54- var json = JsonSerializer . Serialize ( lastState ) ;
55- await File . WriteAllTextAsync ( LastStatePath , json ) ;
56- logger . LogInformation ( "Saved {LastStatePath} with {LastState}" , LastStatePath , lastState ) ;
50+ logger . LogInformation ( "Still playing music...saving current song and queue" ) ;
51+ var lastState = new LastState
52+ {
53+ CurrentSong = player . Status . CurrentSong ,
54+ Queue = player . SongQueue
55+ } ;
56+ var json = JsonSerializer . Serialize ( lastState ) ;
57+ await File . WriteAllTextAsync ( LastStatePath , json , cancellationToken ) ;
58+ logger . LogInformation ( "Saved {LastStatePath} with {LastState}" , LastStatePath , lastState ) ;
59+ }
60+ else //if we're not playing anything right now
61+ {
62+ logger . LogInformation ( "Not playing anything, no state to save." ) ;
63+ if ( File . Exists ( LastStatePath ) ) //don't leave behind a file as if we were.
64+ File . Delete ( LastStatePath ) ;
65+ }
66+ }
67+ catch ( OperationCanceledException )
68+ {
69+ logger . LogWarning ( "Shutdown was cancelled before state could be saved" ) ;
70+ }
71+ catch ( Exception ex )
72+ {
73+ logger . LogError ( ex , "Error saving application state during shutdown" ) ;
5774 }
58- else //if we're not playing anything right now
75+ finally
5976 {
60- logger . LogInformation ( "Not playing anything, no state to save." ) ;
61- if ( File . Exists ( LastStatePath ) ) //don't leave behind a file as if we were.
62- File . Delete ( LastStatePath ) ;
77+ // Ensure music player is properly disposed
78+ if ( player is IDisposable disposablePlayer )
79+ {
80+ try
81+ {
82+ disposablePlayer . Dispose ( ) ;
83+ logger . LogInformation ( "Music player disposed successfully" ) ;
84+ }
85+ catch ( Exception ex )
86+ {
87+ logger . LogError ( ex , "Error disposing music player" ) ;
88+ }
89+ }
6390 }
6491 }
6592
0 commit comments