Search code examples
c#.netwpfsilverlightplaylist

What is the difference between GoToPlaylistItem and GoToPlaylistItemOnNextTick


Unable to understand the difference bettwen GoToPlaylistItem and GoToPlaylistItemOnNextTick, though GoToPlaylistItemOnNextTick clicked on scenarios where GoToPlaylistItem din't work.

If you wonder if there are any differences, Have a look at this Post for a problem solved by using GoToPlaylistItemOnNextTick while it was throwing null exception with GoToPlaylistItem

While I naviaged to the defination I got the following details. Could some one explain?

[ScriptableMember]
public virtual void GoToPlaylistItem(int playlistItemIndex);
public void GoToPlaylistItemOnNextTick(int playlistItemIndex);

Solution

  • MediaPlayer uses a Timer internally. This timer is created in a protected method called CreatePositionTimer:

    protected void CreatePositionTimer(TimeSpan interval)
    {
        if (m_timer == null)
        {
            m_timer = new DispatcherTimer();
            m_timer.Interval = interval; // 6 NTSC frames
            m_timer.Tick += new EventHandler(OnTimerTick);
        }
    }
    

    The method GoToPlaylistItemOnNextTick simply sets a few internal variables:

    public void GoToPlaylistItemOnNextTick(int playlistItemIndex)
    {
        if (!m_goToItemOnNextTick) // don't set it if already set
        {
            m_goToItemOnNextTick = true;
            m_goToItemOnNextTickIndex = playlistItemIndex;
        }
    }
    

    The next time the timer comes around, OnTimerTick is called, and this checks for the above variables and then calls GoToPlaylistItem:

    void OnTimerTick(object sender, EventArgs e)
    {
        [...]
    
        if (m_goToItemOnNextTick)
        {
            m_goToItemOnNextTick = false;
            GoToPlaylistItem(m_goToItemOnNextTickIndex);
        }
    
        [...]
    }
    

    So the difference is that GoToPlaylistItem will go to the next playlist item immediately, while GoToPlaylistItemOnNextTick will do it at the next timer tick. The specific timer it uses is System.Windows.Threading.DispatcherTimer. This ensures that GoToPlaylistItem will be called when the UI thread is idle.

    The difference may be significant if you rely on some of the events that MediaPlayer fires, for example StateChanged. If you call GoToPlaylistItem, this event will execute immediately before GoToPlaylistItem returns. If you call GoToPlaylistItemOnNextTick, then the event will only occur later when your current method has finished and the UI thread is idle.