InvalidOperationException when setting track properties from a BackgroundAgent on Windows Phone

This is just a feature that I stumbled upon when I was updating my radio app I wanted to add an enhancement, so that when the radio was playing I wanted to display the current song on the lock screen (UVC).

This should be very simple and just a matter of setting the information on the current track. So back in Visual Studio I wrote the following code:

BackgroundAudioPlayer.Instance.Track.Artist = "Artist";     
BackgroundAudioPlayer.Instance.Track.Title = "Title";     

And this all compiled fine enough. But when I started retesting my app, I got an InvalidOperationException, which seemed quite curious.

After a bit of googling though I found the answer, which was actually quite simple. For some reason when you call BackgroundAudioPlayer.Instance.Track you do not always get the same object (at least not when doing it from a BackgroundAgent), so in effect that means, that when you call BeginEdit, you do that on one object, but then when you try setting the artist you get another object, which is not in edit mode and therefore the invalidoperation exception.

Solving it was fairly easy and just required copying the current track to a local variable and working on it there, and then everything is running smoothly. So my code ended up like this and the problem was solved:

var track = BackgroundAudioPlayer.Instance.Track;
track.Artist = "Artist";     
track.Title = "Title";     
Comments are closed