c# - 短弱引用和长弱引用有什么区别?

标签 c# garbage-collection weak-references

我知道以下知识:

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

所以如果对象被回收了,需要的时候就得重新创建。

那么,short weak reference 和 long weak reference 有什么区别呢?我认为如下:(根据msdn)

short weak reference: if GC reclaim the object, the object is really released.

long weak reference: if GC reclaim the object, the object is still existed (as it is cached).

那么有人可以告诉我更多细节吗?

最佳答案

Short

The target of a short weak reference becomes null when the object is reclaimed by garbage collection. The weak reference is itself a managed object, and is subject to garbage collection just like any other managed object. A short weak reference is the default constructor for WeakReference.

Long

A long weak reference is retained after the object's Finalize method has been called. This allows the object to be recreated, but the state of the object remains unpredictable. To use a long reference, specify true in the WeakReference constructor.

If the object's type does not have a Finalize method, the short weak reference functionality applies and the weak reference is valid only until the target is collected, which can occur anytime after the finalizer is run.

To establish a strong reference and use the object again, cast the Target property of a WeakReference to the type of the object. If the Target property returns null, the object was collected; otherwise, you can continue to use the object because the application has regained a strong reference to it.

Guidelines for Using Weak References

Use long weak references only when necessary as the state of the object is unpredictable after finalization. Avoid using weak references to small objects because the pointer itself may be as large or larger.

Avoid using weak references as an automatic solution to memory management problems. Instead, develop an effective caching policy for handling your application's objects.

Reference

关于c# - 短弱引用和长弱引用有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17543129/

相关文章:

c# - 从 EPS 文件中提取 XMP 元数据

swift - Swift 中的 weak vs unowned。内部差异是什么?

swift - 为什么UIView动画闭包中的弱自引用导致Swift编译错误

javascript - ES6 Set 和 WeakSet 有什么区别?

c# - 自动部署到具有不同 app.config 设置的许多服务器?

c# - Progressbar 不报告进度

c# - MonoTouch UIButton、UIPickerView 和重写只读 InputView

Android 垃圾收集器 Nursery Full

java - GarbageCollectorMXBean Full GC CollectionCount 和 CollectionTime

garbage-collection - Kotlin 的 Float、Int 等是否针对 JVM 中的内置类型进行了优化?