首页 文章

如何释放MediaElement使用的内存

提问于
浏览
1

我正在使用MediaElement长时间循环显示视频片段 . 经过一段时间(Win 7/4 GB RAM的小时数)后,程序崩溃,“内存不足”类型除外 . 我已经监视了使用Process Explorer-Sysinternals时使用的内存,并使用System.Diagnostics.Process方法记录了它 . 两种方式都表明使用的内存逐渐增加 .

这是代码:

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; } }

}

我还测试了MediaElement对象在多个剪辑之后被动态创建,销毁(以及所有取消订阅事件等)并再次创建的情况 . 记忆力再次消耗殆尽 .

任何建议,将不胜感激!

1 回答

  • 0

    我的建议是做以下事情:

    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();
    }
    

相关问题