This is about a problem that i have faced during the development of an asp.net application. In a certain scenario there was a need for us to create multiple threads manually inside an asp.net application. We created this using the below code
Thread Th = new Thread (TimeTakingTask)
Th.Start();
Now everything worked fine as expected in Microsoft Visual Studio ide and there was no problem until i deployed my code in webserver which was IIS. After deploying to IIS the manual thread was not getting invoked or executed regardless whatever we do. These manual threads always used to get pre-empted or killed before it executes. It really took a while before we found out what exactly we need to do to make these threads work.
The problem was that the child threads was not getting enough permissions to execute and the credentials was not getting copied from the parent thread automatically. Also we did't find any property for thread object to which we can assign or copy the impersonation context .Finally we ended up doing the following code which allowed the manual thread to execute. The idea is to pass the an initialised windowsidentity object from the parent thread to the target method which we are going to create as new thread and then do a normal Impersonation there inside the target C# method. The C#.net code illustration is given below.
I have declared the below variable before initiating a manual thread from the ASP.net page
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
Now go for the manual thread creation and execution and do a Impersonation inside the Method which will get called as a new thread
Thread Th = new Thread (TimeTakingTask)
Th.Start(identity);
private void TimeTakingTask(object stateInfo)
{
System.Security.Principal.WindowsIdentity identity = stateInfo as WindowsIdentity ;
identity.Impersonate();
// your rest of the code goes here
}
Now the thread will work as expected even though it is deployed in IIS. Hope this helps you...
Was this post helpful to you ? !!.. Then please like this in any of the social media below !.
Let it be useful for others too..