过去,调试时我一直被“访问器中的副作用”问题困扰;这意味着我已经在没有触发断点的情况下初始化了缓存(因为它已经在 visual studio 中暂停了)。因此,我一直想知道 Visual Studio 用来“乱序”执行代码的机制,以便在调试器中评估属性。在我看来,这会绕过 CLR 吗?
那么问题来了:从技术角度来看,这是如何做到的?解释它的文章会有所帮助。
最佳答案
看起来像 VS2012(可能还有更早的版本)使用“主线程”或可能是命中断点的线程来执行属性的 getter。
这是我的测试代码:
static class TestSideEffects
{
public static void Test()
{
Console.WriteLine("Main Thread: {0}", Thread.CurrentThread.ManagedThreadId);
var o = new TestSubject();
Console.WriteLine("Property Value: {0}", o.IntGetValueNoSe());
}
}
class TestSubject
{
private int _prop=0;
public int TheProperty
{
get
{
Console.WriteLine("Thread accessing the property: {0}", Thread.CurrentThread.ManagedThreadId);
return ++_prop;
}
}
public int IntGetValueNoSe(){return _prop; }
}
我设置了两个断点:在 Test 方法的第 3 行和 getter 本身,每次我将鼠标悬停在 o 实例上时 - 它会执行 getter 而不会触发另一个断点。它使用相同的(在本例中为 main)线程。
这是测试程序的输出:
Main Thread: 8
Thread accessing the property: 8
Thread accessing the property: 8
Thread accessing the property: 8
关于c# - 在 C# 中调试时,Visual Studio 如何评估属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13963820/