问题
I am maintenancing a WPF application. I added a UWP nedia player on my project. But, memory usage is too high. I realized that UWP media player did it, so I created a reproducible code.
while (true)
{
var mp = new MediaPlayer()
{
Source = MediaSource.CreateFromUri(new Uri("Test.mp4"))
};
Thread.Sleep(1000);
mp.Play();
Thread.Sleep(1000);
mp.Dispose();
}
This code occurs a memory leak. I created MediaPlayer and Disposed it! But, its memory usage grows up infinitely.
How can I catch memory leak on this code?
This is .NET Core 3.0 project. (XAML islands with WPF) I didn't test that if it occurs in pure UWP project, yet.
Someone says that it is natural because it is a loop. But, below code doesn't make any memory leak because GC works. (Of course, some (but limitative) references will be not collected.)
while (true)
{
new SomeClass();
}
回答1:
The way your code is written memory will bloat and grow until you run out of memory. I verified also in pure UWP. If you make the following two changes you will find that the memory will remain stable and the system will reclaim all memory after each loop:
- Dispose also of the MediaSource object you create and assign to the Source property
- Don't run this in a tight loop, instead invoke yourself as a dispatcher action
Here is the code (tested in UWP) that doesn't show any leak. In WPF the Dispatcher call would look slightly different:
private async void PlayMedia()
{
var ms = MediaSource.CreateFromUri(new Uri("ms-appx:///Media1.mp4"));
var mp = new MediaPlayer()
{
Source = ms
};
Thread.Sleep(1000);
mp.Play();
Thread.Sleep(1000);
mp.Dispose();
ms.Dispose();
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(PlayMedia));
}
As a side note: the "SomeClass" comparison you mentioned isn't exactly an apples-to-apples to comparison if SomeClass is a pure managed code class, as the objects you are creating here are complex native Windows Runtime objects that only have a thin managed code wrapper around them.
Tested also now in WPF: I reproduced the original memory growth issue, then applied the suggested changes and verified that the memory no longer grows. Here is my test project for reference: https://1drv.ms/u/s!AovTwKUMywTNuLk9p3frvE-U37saSw
Also I ran your shared solution with the WPF app packaged as a Windows App Package and I am not seeing a leak on the latest released version of Windows 10 (17763.316). Below is a screenshot of the memory diagnostics after running your solution for quite a while. If this is specific to the insider build you are running, please log a bug via Feedback Hub. I think at this point we should close this question as answered.
回答2:
It is absolutely a bug of Windows 10 19H1. Because built-in app (Movie and TV) has same memory leak issue. To reproduce this, just repeat that open video file and close it.
来源:https://stackoverflow.com/questions/54725337/memory-leak-on-uwp-mediaplayer-windows-media-playback-mediaplayer