-
In console app, I use the below code. Why I get two 'True' on console screen? var weak = new WeakReference<StringBuilder>(new StringBuilder());
Console.WriteLine(weak.TryGetTarget(out _));
GC.Collect();
Console.WriteLine(weak.TryGetTarget(out _)); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
This is not guaranteed to work the way you expect it, especially when it's called in the same method as it depends on the optimizations level (Tier0/Tier1) of the current method (namely, precise liveness analysis) and whether GC in general is precise or not on the given runtime. You may rewrite your repro to call TryGetTarget in different methods or put |
Beta Was this translation helpful? Give feedback.
This is not guaranteed to work the way you expect it, especially when it's called in the same method as it depends on the optimizations level (Tier0/Tier1) of the current method (namely, precise liveness analysis) and whether GC in general is precise or not on the given runtime. You may rewrite your repro to call TryGetTarget in different methods or put
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
on the current method, but it's better to not depend on this anyway.