.netmultithreadingcurrent-principal

In .NET, System.Threading.Thread.CurrentPrincipal isn't updating


I'm missing something elementary here when debugging some .NET code:

    public static void CreateServiceSessionStore()
    {
        ServiceSessionStore serviceSessionStore = new ServiceSessionStore();
        serviceSessionStore.SetIdentity(System.Threading.Thread.CurrentPrincipal.Identity);
        System.Threading.Thread.CurrentPrincipal = serviceSessionStore;
        // Here, CurrentPrincipal still isn't a serviceSessionStore!
    }

In this code, everything seems to chug merrily along. However...when I debug and am just before the last line, I'm looking at System.Threading.Thread.CurrentPrincipal. The value is a WebSessionStore object, which is what I expect, and what I am thinking the last line should change it to a ServiceSessionStore object. But it doesn't. I can look at serviceSessionStore, and it's holding a ServiceSessionStore object, but after the line runs CurrentPrincipal still contains a WebSessionStore object. No error is thrown.

Now, aside from what these objects actually do, can someone offer an idea about why it seems to be refusing to update CurrentPrincipal?


Solution

  • This is a debugger artifact. Debug expressions are evaluated on a dedicated debugger thread. CurrentPrincipal is a property of the thread's execution context. Also the reason it can be a static property. Different threads will have different principals and the debugger thread's principal is therefore not the same.

    You don't have a real problem.