MDimitrov
MDimitrov

Reputation: 51

How to release memory used by MediaElement

I am using MediaElement to show video clips in a loop for long period of time. After some time (hours for Win 7 / 4 GB RAM) the program crashes with exception of type "Insufficient memory". I have monitored the memory used while playing with Process Explorer-Sysinternals and also logged it using System.Diagnostics.Process methods. Both ways show gradually increasing of used memory.

Here is the code:

XAML:

<Grid Name="GridTest">
    <MediaElement x:Name="MediaPlayer"
                  LoadedBehavior="Manual"
                  MediaEnded="VideoControl_MediaEnded"
                  MediaOpened="MediaPlayer_MediaOpened"
                  Source="{Binding Mode=OneWay,
                                   Path=MySource}" />
</Grid>

.cs:

public partial class MainWindow : Window
{
    public MainViewModel model = new MainViewModel();

    public MainWindow()
    {
        InitializeComponent();

        this.GridTest.DataContext = model;

        // fill in model.MediaFilesUris:
        ...
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // choose the next media file 
        ...

        MediaPlayer.Play();
    }

    private void VideoControl_MediaEnded(object sender, RoutedEventArgs e)
    {
        // choose the next media file 
        ...

        model.OnPropertyChanged("MySource");

        MediaPlayer.Play();
    }
}


public class MainViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    { 
      PropertyChangedEventHandler handler = PropertyChanged;
      if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); 
    }

    public Uri[] MediaFilesUris = null;
    public int crn = 0;

    public Uri MySource { get { if (MediaFilesUris != null && MediaFilesUris.Count()>0) return MediaFilesUris[crn]; else return null; } }

}

I have also tested the case when MediaElement object is created dynamically, destroyed (together with all unsubscribing from events, etc.) after several clips and created again. Memory got consumed increasingly again.

Any suggestions would be appreciated!

Upvotes: 2

Views: 3168

Answers (2)

Karen Tsirunyan
Karen Tsirunyan

Reputation: 1998

Try to specify MediaElement UnloadingBehavior="Close"property in your XAML.

According to MSDN MediaState::Close indicates that

All media resources are released (including video memory).

Upvotes: 2

EngineerSpock
EngineerSpock

Reputation: 2675

My proposal is to make the following:

private void VideoControl_MediaEnded(object sender, RoutedEventArgs e)
{
    // choose the next media file 
    ...
    //make the following explicitly
    MediaPlayer.Stop();      
    MediaPlayer.Source = null;

    model.OnPropertyChanged("MySource");

    MediaPlayer.Play();
}

Upvotes: 0

Related Questions