I have some troubles with memory leak. Here's my test code:
// Create the object
string book = "This is a book";
Debug.WriteLine(book);
// Set weak reference
WeakReference wr = new WeakReference(book);
// Remove any reference to the book by making it null
book = null;
if (wr.IsAlive)
{
Debug.WriteLine("Book is alive");
var book2 = wr.Target as string;
Debug.WriteLine("again -> " + book2);
book2 = null;
}
else
Debug.WriteLine("Book is dead");
// Lets see what happens after GC
GC.Collect();
GC.WaitForPendingFinalizers();
// Should not be alive
if (wr.IsAlive)
Debug.WriteLine("again -> Book is alive");
else
Debug.WriteLine("again -> Book is dead");
And output is:
This is a book
Book is alive
again -> This is a book
again -> Book is alive
So, why "wr" still alive after call GC.Collect()? Anything wrong with GC? I'm run on WP8 & WP8.1 preview. Can you help me.