Can someone please explain why the following program runs out of memory?
class Program
{
private static void ThreadRoutine()
{
System.Windows.Media.MediaPlayer player = new System.Windows.Media.MediaPlayer();
}
static void Main(string[] args)
{
Thread aThread;
int iteration = 1;
while (true)
{
aThread = new Thread(ThreadRoutine);
aThread.Start();
aThread.Join();
Console.WriteLine("Iteration: " + iteration++);
}
}
}
To be fair, the specific exception I get is a System.ComponentModel.Win32Exception
, "Not enough storage is available to process this command." The exception happens on the attempt to create a new MediaPlayer.
MediaPlayer does not implement the IDisposable
interface so I'm not sure if there is other cleanup necessary. I certainly didn't find any in the MediaPlayer documentation.
I had an application long ago, which rendered data to image, and placed it over a PictureBox as result, like a pipe line of graphical engine, ...
The thing ware in common with you, were the lack of memory, it was like this,...
And a lot of Auto Garbage Collecting at high memory around 90% to 97%,... but seem it wasn't enough, and at some point around 97% and 98% system (application) crashed with memory issue...
so i come with this idea, to call garbage collector every several frame, so i did this: GC.Collect();
GC.Collect it self is to heavy, also when there are too many object inside memory,... but when you don't left too many object, it work smooth,...
there are also many thing about finalizing objects, but I'm not sure if they work properly, as they naturally end in -> x = null
which mean, we broke the link to that object, but doesn't mean we do not have this object some where around galaxy (for example you can fill object destructor with a message, and see after leaving that object it won't get destroyed immediately, it take till you close your application / call GC.Collect / Lack on memory, or maybe random auto collect),... until it get destroyed,... so, for example as the "using" directive, it self call "Dispose" method, and we fill our dispose with obj= null,... then i'm not sure if i should recommend you writing manual finalize method, but there's still one thing... there's a Marshal object, which i don't know where it come from, and if it work over all object, i see some programmer use it to release objects, ..., i don't know how it work, but it maybe really release the object from our memory,...
If you did not found anything useful about it, my first option will be calling GC.Collect...
also you can set it's parameters, so it collect less object, than it would do normally.
https://msdn.microsoft.com/en-us/library/xe0c2357%28v=vs.110%29.aspx
Release resources in .Net C#
i also didn't read this fully, but seem he has thread and memory issue: Freeing resources when thread is not alive
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With