Are multiple WeakReferences to the same object always in sync?
If there are more than o开发者_运维技巧ne WeakReference pointing to the same object, will they always be cleared at the same time, or may they be out of sync. A small example to illustrate:
var o = new Object();
var weak1 = new WeakReference(o);
var weak2 = new WeakReference(o);
for (int i = 0; i < 10000; i++) {
GC.Collect();
Debug.Assert(weak1.IsAlive == weak2.IsAlive);
}
P.S. The above snipped runs fine (the assert is not triggered). Also the questions is really (at least) two separate issues:
- Are they cleared approximately at the same time (not thread safe)?
- Are they cleared in a thread safe manner?
Here in your question, weak1.IsAlive
always equals to weak2.IsAlive
, because WeakReference.IsAlive gets an indication whether the object referenced by the current WeakReference object (or say, WeakRefernce.Target) has been garbage collected. The two WeakReference have the same target object. But be aware of that weak1/weak2 themselves are also reference type, they are not reference equal, but their targets are the same.
精彩评论