2012-12-20 41 views
9

過去,在調試過程中,我一直被「附帶副作用」問題所困擾;這意味着我有緩存被初始化而沒有觸發我的斷點(因爲它已經在visual studio中暫停了)。所以我一直想知道Visual Studio用來「亂序」執行代碼的機制,以便在調試器中評估屬性。在我看來,這會繞過CLR?Visual Studio在C#中調試時如何評估屬性?

所以問題:從技術的角度來看,這是如何完成的?文章解釋它會有所幫助。

+0

我似乎記得橫跨其上的一篇文章到來前一段時間,但我的谷歌福太薄弱了,再次找到它。 – Smashery

+0

要啓動[副作用和表達式](http://msdn.microsoft.com/zh-cn/library/a7a250bs.aspx) – horgh

回答

2

看起來像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; } 
} 

我設置了兩個斷點:在試驗方法的第3行,並在吸氣劑本身,每一次我懸停我的鼠標移到鄰實例時 - 它執行吸氣劑不觸發另一個斷點。它使用相同的(主要在這種情況下)線程。

這是測試程序的輸出:

Main Thread: 8 
Thread accessing the property: 8 
Thread accessing the property: 8 
Thread accessing the property: 8 
相關問題