How are weak references and strong references implemented in C#?

In C#, weak references and strong references can be implemented using the WeakReference and Reference classes.

A strong reference is the most common type of reference, which keeps a reference to an object and prevents it from being garbage collected as long as the strong reference exists. You can create a strong reference using regular variables.

MyObject obj = new MyObject(); // 创建一个强引用

Weak reference is a special type of reference that does not prevent an object from being garbage collected. The WeakReference class can be used to create weak references.

WeakReference weakRef = new WeakReference(obj); // 创建一个弱引用

The WeakReference class offers a way to access the object pointed to by a weak reference, but it is necessary to check if the object has already been garbage collected before using it.

if (weakRef.IsAlive)
{
    MyObject obj = (MyObject)weakRef.Target; // 获取弱引用所指向的对象
    // 使用对象
}
else
{
    // 对象已被垃圾回收
}

Weak references are suitable for scenarios where objects need to be monitored but should not prevent them from being garbage collected, such as implementing caches, event subscriptions, and so on.

It’s important to note that the object pointed to by a weak reference may be garbage collected at any time, so it’s important to handle the case where the object is null carefully when using weak references.

bannerAds