Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Visual Studio evaluate properties while debugging in C#?

In the past, I've been burned by the "side-effects-in-an-accessor" issue when debugging; meaning that I've had caches being initialised without my breakpoints being triggered (since it was already paused in visual studio). And so I've been wondering about the mechanism that Visual Studio uses to execute code "out-of-order", so as to evaluate properties in a debugger. It would seem to me that this would circumvent the CLR?

So the question: How is this done from a technical standpoint? Articles explaining it would be helpful.

like image 718
Smashery Avatar asked Dec 20 '12 01:12

Smashery


1 Answers

Looks like VS2012 (and probably earlier versions as well) executes the property's getter using the "Main Thread" or maybe the thread that hit the breakpoint.

This is my testing code:

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; }
}

I set two breakpoints: on the 3rd line of the Test method and in the getter itself, and every time I hover my mouse over the o instance - it executes the getter without triggering the other breakpoint. It uses the same (main in this case) thread.

This is the output of the test program:

Main Thread: 8
Thread accessing the property: 8
Thread accessing the property: 8
Thread accessing the property: 8
like image 95
Zar Shardan Avatar answered Sep 23 '22 19:09

Zar Shardan