c# - wpf MediaElement 内存泄漏

标签 c# wpf mediaelement

我正在使用媒体元素来显示多种资源(图像、gif、视频)

问题是,每次我为其分配新源时,媒体元素都会消耗更多内存。 垃圾收集器没有在那里收集任何东西。我在论坛和堆栈溢出中发现了几个关于同一主题的问题,但没有一个得到正确的答案。

这是我的 wpf 代码:

private void LoadInformation(FileInfo file)
{
    imageDisplay.Source = new Uri(file.FullName);
}

<MediaElement x:Name="imageDisplay" Grid.Column="0" Grid.Row="0" UnloadedBehavior="Close" LoadedBehavior="Manual"
            MediaOpened="Element_MediaOpened" MediaEnded="Element_MediaEnded" ></MediaElement>

这是我要在 .xaml.xs 中更新的代码:

// When the media opens, initialize the "Seek To" slider maximum value
// to the total number of miliseconds in the length of the media clip.
private void Element_MediaOpened(object sender, EventArgs e)
{
    imageDisplay.Play();
}

// When the media playback is finished. Stop() the media to seek to media start.
private void Element_MediaEnded(object sender, EventArgs e)
{
    imageDisplay.Stop();
    imageDisplay.Source = null;
}

这是根据微软官方文档: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-control-a-mediaelement-play-pause-stop-volume-and-speed?view=netframeworkdesktop-4.8

如果我在循环中执行LoadInformation,我的内存会愉快地上升,直到应用程序崩溃。

如果我在应用程序崩溃之前停止循环并让它运行一段时间,gc 将不会释放内存 enter image description here

更新 1

手动管理 MediaElement 没有任何区别: LoadedBehavior = MediaState.Manual;

imageDisplay.Stop();
imageDisplay.Close();
imageDisplay.Source = null;
imageDisplay.Source = new Uri(file.FullName);
imageDisplay.Play();

enter image description here

最佳答案

经过两天的搜索并没有找到任何可行的解决方案,我至少找到了一些提示。

问题:

对以下信息持保留态度。

我认为发生的事情是 MediaElement 是 WPF 中包装的 Winforms 的旧版组件。我看到了一些提示,例如将源从流更改为 uri。 引起我注意的是一些方法,例如 mediaelement.Finalize() 被删除了。
我最好的猜测是,现在不应该再使用 MediaElement 了?

解决方案

如上面的屏幕截图所示,显示 84kb jpg 的 64gb 内存消耗是无可争议的。我已经四处寻找替代方案。
对我来说足够证明的是 WebView2 控件。

用法:

<wpf:WebView2 x:Name="ImageWebView" Grid.Column="0" Grid.Row="0"></wpf:WebView2>
ImageWebView.Source = new Uri(CollectionInformation.Information.NftPreviewFiles[key].FullName);

现在没有发现任何内存影响: enter image description here

不幸的是,WebView2 是一个 nuget 包,尽管来自微软。 可以通过名称 Microsoft.Web.WebView2

找到它

我希望这可以帮助别人

关于c# - wpf MediaElement 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74695045/

相关文章:

c# - 如何使用 C# 访问 SQLite?

c# - Entity Framework 子级为空

wpf - 注册嵌入式 DirectShow 过滤器

c# - MediaElement 是否仅在嵌入到 XAML 代码中时才播放?

c# - 关闭浏览对话框导致窗体关闭

c# - 授权属性不起作用

c# - 将 child 添加到 UserControl

c# - Datagrid selectedItem 和数据绑定(bind)

wpf - 我可以在 DataGrid 表之间共享 DataGrid.Columns

c# - 如何在 wpf c# 中播放双音频电影