Running an impersonated background thread in ASP.Net

by Rob 23. April 2010 11:43

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.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Powered by BlogEngine.NET 1.4.0.0
Theme by Mads Kristensen

About the author

Some text that describes me

Recent comments

Comment RSS

Page List

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

    © Copyright 2008