Are there weak links in .NET?

I would like to keep a list of a specific class of objects in my application. But I still want the object to be garbage collected. Can you create weak links in .NET?

For reference:

Reply From MSDN:

To establish a weak link using an object, you create a WeakReference using an instance of the object to be tracked. Then you set the target property for this object and set object to null. For sample code, see WeakReference in the class library.

+4
source share
4 answers

Yes, there is a common weak reference class.

MSDN> Weak Link

+12
source

Can you create weak links in .NET?

Yes:

WeakReference r = new WeakReference(obj); 

Uses System.WeakReference .

+5
source

Here is a complete implementation example (insecure) of WeakReference implementation

 ClassA objA = new ClassA(); WeakReference wr = new WeakReference(objA); // do stuff GC.Collect(); ClassA objA2; if (wr.IsAlive) objA2 = wr.Target as ClassA; else objA2 = new ClassA(); // create it directly if required 

WeakReference is located in the System namespace, so there is no need to include any special assembly in it.

0
source

All Articles