【发布时间】:2014-07-23 08:17:39
【问题描述】:
我遇到了一些内存泄漏问题。 这是我的测试代码:
// 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");
输出是:
This is a book
Book is alive
again -> This is a book
again -> Book is alive
那么,为什么在调用 GC.Collect() 之后“wr”仍然存在? GC有什么问题吗? 我在 WP8 和 WP8.1 预览版上运行。 你能帮帮我吗?
【问题讨论】:
标签: c# windows-phone-8 memory-leaks garbage-collection