oatsoda
oatsoda

Reputation: 2178

Winforms main UI thread principal reverting to previous

I am working on a Winforms app that uses the CSLA framework with custom authentication (i.e. The middle tier/server manages authentication) and am in the process of implementing a Session Timeout feature.

The problem I am having is a weird issue with the Principal. When I log in after a session times-out, I create a new Principal object (my own custom Principal object). This gets assigned to the current thread, which is always the UI thread (I have checked and am also using Control.Invoke to ensure the login form is run on the UI thread, and the click event of this form runs on the UI thread).

However, after this, when I click on a button in the UI I can see that the Principal has reverted back to the OLD Principal.

Is there any reason or any condition where the Main UI Thread would be able to revert back to the previous Principal?

Are there any known gotchas to avoid around the Principal on the Main UI Thread?

I have checked and I'm not setting the Thread.CurrentPrincipal anywhere else.

UPDATE

I have solved this issue by changing to a Windows.Forms.Timer to trigger my session timeout, rather than previously I was using a System.Timers.Timer and then using Control.Invoke where required. When I change this, then the Principal I set on the UI thread is still there the next time something executes on the UI thread.

Can anyone explain this? So essentially it seems like setting the Principal on the UI thread can mean two different things...is there some kind of context that I need to be sure of when setting it?

I've found a couple of other people having what appears to be the same issue...

http://permalink.gmane.org/gmane.comp.windows.devel.dotnet.advanced/14046 https://groups.google.com/forum/#!topic/microsoft.public.dotnet.languages.csharp/_hLhcDB3jHA

Upvotes: 3

Views: 371

Answers (1)

Andy
Andy

Reputation: 8562

I believe what is happening is that with the system timer your code actually is executed on a separate thread, and EACH thread in .net can have its own principal set (its ThreadStatic, if you're familiar with that attribute). The Windows timer however will run your timer code in the ui thread which you've set the principal on. Note that while your timer code is running the ui is not responsive as no message pumping can happen, so if your code can take awhile you'd want to go back to the system timer.

To make new threads see the same principal you should look at https://msdn.microsoft.com/en-us/library/system.appdomain.setthreadprincipal(v=vs.110).aspx as well as the SetPrincipalPolicy method also on the AppDomain.

Upvotes: 1

Related Questions