c# - 如何释放 MediaElement 使用的内存

标签 c# wpf mediaelement

我正在使用 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 对象动态创建、在几个剪辑后被销毁(以及所有取消订阅事件等)并再次创建的情况。内存消耗再次增加。

如有任何建议,我们将不胜感激!

最佳答案

尝试在 XAML 中指定 MediaElement UnloadingBehavior="Close" 属性。

根据 MSDN MediaState::Close 表明

All media resources are released (including video memory).

关于c# - 如何释放 MediaElement 使用的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35873942/

相关文章:

c# - 当表存在时,代码优先 EntityFrameworkCore.Sqlite 3.1.1 上为 "No such table"

c# - 如何 XML 序列化对象列表数组?

c# - 了解数据绑定(bind)如何在 UserControl 的 DependencyProperty 及其宿主应用程序的属性之间工作

c# - 绑定(bind)文本框 enter press to reactive command

c# - 带有 Mvvm Light 处理鼠标和触摸的 WPF

c# - 创建物体之间的时间距离统一

javascript - 如何使用 C# 或 JavaScript 等代码触发元素点击?

c# - WPF MediaElement 视频卡住

audio - 播放单音音频文件的最佳方法?

c# - wpf MediaElement 内存泄漏