thewizrd / iTunes-SMTC

Integrates iTunes with Windows 10/11 system media controls
MIT License
11 stars 2 forks source link

Not fully releasing iTunes COM object #3

Open AD4MANTIS opened 2 years ago

AD4MANTIS commented 2 years ago

I recently tried using your App and it works great so thank you. However, I noticed a bug where the _iTunesApp object wasn’t correctly destroyed when closing iTunes. This causes iTunes to display a Popup that an App is still using the iTunes interface and waits 20 before closing automatically.

Steps to reproduce:

  1. Start the iTunes-SMTC App
  2. Start iTunes
  3. Press Play to start a song
  4. Close iTunes
  5. The above-mentioned message appears

I had a look at the code myself and found this Code in the DisconnectiTunes() method: https://github.com/thewizrd/iTunes-SMTC/blob/d2cb03e86a54957ee967d0b15926e5a200f22685/iTunes.SMTC/SettingsUi.iTunesController.cs#L409-L423 I had a similar problem with iTunes but I got it fixed by using Marshal.FinalReleaseComObject and GC.Collect();:

if (_iTunesApp != null)
{
    Debug.WriteLine("Releasing iTunes COM object...");
    wasAlive = true;
    RemoveEvents();
    Marshal.FinalReleaseComObject(_iTunesApp);
    GC.Collect();
}
_iTunesApp = null;
if (_currentTrack != null)
{
    Marshal.FinalReleaseComObject(_currentTrack);
    GC.Collect();
}
_currentTrack = null;

You can try the the Fix in my fork here: https://github.com/AD4MANTIS/iTunes-SMTC The relevant comit is here: https://github.com/AD4MANTIS/iTunes-SMTC/commit/a4db4196596f62e8e9b4ea55e48c904a54ab2638

For me this fix works when I open the settings UI once before playing the first song with iTunes. The UI doesn’t need to be open when pressing play to work. It’s the same thing when opening iTunes again after closing it. If I don’t open the settings UI before playing the first song it gives me the message, otherwise it closes normally.

I'm not sure what causes this, so maybe do you have an idea?

thewizrd commented 2 years ago

Hi,

Thanks for this. I've noticed this issue as well.

Previously, the disconnect code was enqueued to the DispatcherQueue/UI Thread. This may have been why if the app was in the foreground it would work, as opposed to if the app was in the background where there might be a delay in execution.

I moved the disconnect code out of the enqueue method and tried to execute it automatically after the "OnAboutToPromptUserToQuitEvent" event is called which seems to help.

The commit for this can be seen here: https://github.com/thewizrd/iTunes-SMTC/commit/18d1a39ffe6547ab1681b8fa43f266995d21c7c7

However, I've noticed that sometimes the "OnAboutToPromptUserToQuitEvent" isn't fired, so this may not always work.