When you want to run a long-running process in ASP.Net, you are bound to get into time-out problems.
Not when running the process in a background thread. Spawning a thread is easy using the System.Threading.Thread namespace
ThreadStart ts = new ThreadStart(this.PerformWork);
_worker = new Thread(ts);
_worker.Start();
…
private void PerformWork()
{
…do your stuff here.
}
When the website is running under impersonation, you’ll have a problem inside the PerformWork method, because the new thread inherits from the parent thread, which is actually running under the ASPNET account!
To solve this, you need to capture the Windows Identity of the impersonated user, and then change the security context inside the thread like so:
ThreadStart ts = new ThreadStart(this.PerformWork);
_worker = new Thread(ts);
_appID = System.Security.Principal.WindowsIdentity.GetCurrent();
_worker.Start();
…
private void PerformWork()
{
WindowsImpersonationContext wi = _appID.Impersonate();
…do your stuff here.
}
Problem solved. The background thread now assumes the identity of the person logged in.