5

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.

John Odom
  • 1,189
  • 2
  • 20
  • 35
Sid G.
  • 143
  • 4
  • What's wrong with letting GC dispose it internally? It looks like `MediaPlayer` is not an `IDisposable` object so you don't have to worry about manually disposing of it. – John Odom May 28 '15 at 19:42
  • This will be a hold-and-catch-fire loop when you debug your code. [This post](http://stackoverflow.com/a/17131389/17034) explains why. Stop helping. – Hans Passant May 28 '15 at 20:37
  • I am debugging a memory leak where MediaPlayer objects are never disposed of. I can't guarantee that references no longer exist but I'm pretty sure they don't so I was trying to devise a test to prove that there is nothing special about them. I was using the WeakReference to test whether they have been disposed of but that wasn't working either. How else can I verify that an object has been disposed of? – Sid G. May 28 '15 at 20:42
  • 1
    Well, not this way. This code doesn't leak of course. When you post fake code that doesn't have anything to do with your real program then nobody can help you. – Hans Passant May 28 '15 at 20:48

1 Answers1

2

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)

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
  • So there is absolutely no way to force the collection? – Sid G. May 28 '15 at 20:48
  • @SidG. Get rid of all references, including the weak reference. Then call `GC.Collect(GC.MaxGeneration);` and `GC.WaitForFullGCComplete(100);` (no guarantee that this works). After that, create a full memory dump. Analyze the dump and find out why the MediaPlayer objects are still rooted (in WinDbg `!dumpheap -type MediaPlayer` and `!gcroot` are a starting point). – Thomas Weller May 28 '15 at 20:53
  • Thanks Thomas, at least this gets me closer and explains the answer to my original question. – Sid G. May 28 '15 at 21:01