Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispose of System.Windows.Media.MediaPlayer

Tags:

c#

The question is simple and can be summed up by:

How can I get this while loop to exit?

System.Windows.Media.MediaPlayer player = new System.Windows.Media.MediaPlayer();
WeakReference test = new WeakReference(player);

player.Close();
player = null;

while (test.IsAlive && test.Target != null)
{
    System.GC.Collect();
}

I have searched the documentation and have found no way to dispose of this object, the while loop never exits.

like image 454
Sid G. Avatar asked Nov 01 '22 03:11

Sid G.


1 Answers

I am surprised that neither the C# documentation nor the Java documentation describes it that clearly:

If there is no memory pressure, a WeakReference will not be collected.

This MSDN article might be helpful:

A weak reference permits the garbage collector to collect the object while still allowing the application to access the object.

Permission is not a requirement. It may do so, but it needn't.

Wikipedia gets it right under Variations (for Java, but Java and C# are quite similar):

[...] the GC may decide not to do so if it believes the JVM can spare the memory (e.g. the JVM has lots of unused heap space)

like image 63
Thomas Weller Avatar answered Nov 10 '22 12:11

Thomas Weller