Reputation: 70983
I would like to keep a list of a certain class of objects in my application. But I still want the object to be garbage collected. Can you create weak references in .NET?
For reference:
Answer From MSDN:
To establish a weak reference with an object, you create a WeakReference using the instance of the object to be tracked. You then set the Target property to that object and set the object to null. For a code example, see WeakReference in the class library.
Upvotes: 4
Views: 3811
Reputation: 14561
Yes...
There is a pretty good example to be found here:
In your class you created two member variables:
WeakReference _weakRef = null;
Person _strongRef = null;
You created two new Person
objects (which are simple objects I just created for this example, consisting of a Name
property and some reference tracking code). Next you set the member variables to the newly created instances of the Person
objects.
_strongRef = p;
_weakRef = new WeakReference(p1);
The difference here you’ll notice that _strongRef
is just a regular normal reference, whereas _weakRef
is set to a WeakReference
object with the person object (p1)
passed in as a parameter in the constructor.
If a garbage collection were to occur, or just for testing purposes you called it yourself with:
GC.Collect();
Then the p1
target object that is held by the _weakRef
member variable should be garbage collected. You can write code to check:
if (_weakRef.IsAlive)
If the WeakReference
is still alive you can convert the WeakReference
to a strong or normal reference by using code like this:
Person p = _weakRef.Target as Person;
Now the p
reference is treated as a strong reference and won’t be collected until it is no longer used. If you wanted to keep the reference around after the scope you could set that to a member variable.
Upvotes: 3
Reputation: 16196
Here is the full (non thread safe) implementation sample of WeakReference
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 in the System
namespace hence no need to include any special assembly for it.
Upvotes: 0
Reputation: 545588
Can you create weak references in .NET?
Yes:
WeakReference r = new WeakReference(obj);
Uses System.WeakReference
.
Upvotes: 5