我正在使用媒体元素来显示多种资源(图像、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;
}
如果我在循环中执行LoadInformation
,我的内存会愉快地上升,直到应用程序崩溃。
如果我在应用程序崩溃之前停止循环并让它运行一段时间,gc 将不会释放内存
更新 1
手动管理 MediaElement 没有任何区别: LoadedBehavior = MediaState.Manual;
imageDisplay.Stop();
imageDisplay.Close();
imageDisplay.Source = null;
imageDisplay.Source = new Uri(file.FullName);
imageDisplay.Play();
最佳答案
经过两天的搜索并没有找到任何可行的解决方案,我至少找到了一些提示。
问题:
对以下信息持保留态度。
我认为发生的事情是 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);
不幸的是,WebView2 是一个 nuget 包,尽管来自微软。
可以通过名称 Microsoft.Web.WebView2
我希望这可以帮助别人
关于c# - wpf MediaElement 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74695045/