Here's something that is really mind boggling. I discover that ConditionalWeakTable is working differently in .Net 7.0 and .Net Framework 4.8.
I get the code straight from here:
public class Program
{
static void Main(string[] args)
{
var mc1 = new ManagedClass();
var mc2 = new ManagedClass();
var mc3 = new ManagedClass();
var cwt = new ConditionalWeakTable<ManagedClass, ClassData>();
cwt.Add(mc1, new ClassData());
cwt.Add(mc2, new ClassData());
cwt.Add(mc3, new ClassData());
var wr2 = new WeakReference(mc2);
mc2 = null;
GC.Collect();
ClassData data = null;
if (wr2.Target == null)
Console.WriteLine("No strong reference to mc2 exists.");
else if (cwt.TryGetValue((ManagedClass)wr2.Target, out data))
Console.WriteLine("Data created at {0}", data.CreationTime);
else
Console.WriteLine("mc2 not found in the table.");
}
}
public class ManagedClass
{
}
public class ClassData
{
public DateTime CreationTime;
public object Data;
public ClassData()
{
CreationTime = DateTime.Now;
this.Data = new object();
}
}
And I make sure that I'm running in Release mode and the "Suppress JIT optimization" option is unticked.
BUT, the output in .Net 7.0 is different than in .Net framework 4.8.
In .Net 7.0, I get this, which indicates that the mc2 's target is still alive even though I've set the mc2 to null.
"Data created at .."
But in .Net 4.8, I get a more sensible result ( this is how ConditionalWeakTable should behave according to my understanding)
"No strong reference to mc2 exists."
In the MSDN document above, it also mentions that the .Net framework 4.8 result is the correct one. But why I'm getting otherwise in .Net 7?