c# – 如何处理System.Windows.Media.MediaPlayer

问题很简单,可以概括为:

如何在循环退出时进行此操作?

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();
}

我搜索了文档,发现没有办法处理这个对象,while循环永远不会退出.

最佳答案 我很惊讶C#文档和Java文档都没有清楚地描述它:

如果没有内存压力,则不会收集WeakReference.

这篇MSDN文章可能会有所帮助:

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

许可不是必需的.它可能会这样做,但它不需要.

Wikipedia在Variations下正确使用(对于Java,但Java和C#非常相似):

[…] 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)

点赞