Hi Guys, I've run into something which I'm struggling to explain. My actual example is quite complicated, and will be difficult to post here without a fairly large chunk of code being posted, so I'll do my best to explain in words:
Basically, in a thick / smart client application, I am trying to perform a login asynchronously. The result of the login is that an instance of a custom class (let's call it MyPrincipal) gets assigned to Thread.CurrentPrincipal. Now, it might be reasonable to assume that since we are on a background thread, once this operation completes, accessing Thread.CurrentPrincipal from another thread (primarily the UI thread) might not return the MyPrincipal instance. OK, so the solution is to set Thread.CurrentPrincipal on the BackgroundWorker.RunWorkerCompleted, right? Well, it doesn't seem to change anything. No exception is thrown, but somehow Thread.CurrentPrincipal just seems to lose its value somewhere between my code setting it, and the next time I trigger an event on the UI. At first, I thought this might be an issue with how BackgroundWorker was implemented, so I invoked a method on the UI thread explicitly using a delegate. Same behavior!? As a work around, I have now resorted to retrieving the MyPrincipal object on the BackgroundWorker, and then setting a class variable to it. I then enable a Windows.Forms.Timer with a short duration (10 ms), which then sets Thread.CurrentPrincipal when the Tick event fires (this is on the UI thread since it’s a WinForms timer). This works 100%, but it's just a bit too cheesy for me to leave in as production code. Is there something I'm missing about threads and / or specifically Thread.CurrentPrincipal? Am I supposed to be using a lock() on it, even though there is only a single thread at any given point which is accessing it? And what exactly is the difference between RunWorkerCompleted, Control.Invoke, and a timer's tick event, since it seems to be making a large difference. My only thought at this point is that it's some kind of timing issue, but I'm not really sure why it would occur. BTW, I ran across this thread with someone experiencing basically the same issue, in the thread they agree that it's strange but can't really explain why it happens either: http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/fe12e17030778c70/7b18d3efff24cc22?lnk=raot Any ideas would be welcome.... Regards, Daniel.