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:
- Garbage Collecting objects which keep track of their own instances in an internal Map
- Create a weak reference to an object
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.
-
Yes, there's a generic weak reference class.
-
Can you create weak references in .NET?
Yes:
WeakReference r = new WeakReference(obj);
Uses
System.WeakReference
. -
Yes...
There is a pretty good example to be found here:
daub815 : FYI, the link above no longer works :(Andrew Rollings : Updated to refer to the wayback machine copy instead. -
Here is the full 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 theSystem
namespace hence no need to include any special assembly for it.
0 comments:
Post a Comment