Identity.Name is disposed in a IIS7 Asp.NET MVC application Thread
- by vIceBerg
I have made the smallest demo project to illustrate my problem. You can download the sources Here
Visual Studio 2008, .NET 3.5, IIS7, Windows 7 Ultimate 32 bits. The IIS Website is configured ONLY for Windows Authentication in an Integreated pipeline app pool (DefaultAppPool).
Here's the problem. I have an Asp.NET MVC 2 application. In an action, I start a thread. The View returns.
The thread is doing it's job... but it needs to access Thread.CurrentPrincipal.Identity.Name
BANG
The worker process of IIS7 stops. I have a window that says:
"Visual Studio Just-In-Time Debugger
An unhandled exception ('System.Object.DisposedException') occured in w3wp.exe [5524]"
I checked with the debugger and the Thread.CurrentPrincipal.Identity is valid, but the Name property is disposed.
If I put a long wait in the action before it returns the view, then the Thread can do it's job and the Identity.Name is not disposed. So I think the Name gets disposed when the view is returned.
For the sake of the discussion, here's the code that the thread runs (but you can also download the demo project. The link is on top of this post):
private void Run()
{
const int SECTOWAIT = 3;
//wait SECTOWAIT seconds
long end = DateTime.Now.Ticks + (TimeSpan.TicksPerSecond * SECTOWAIT);
while (DateTime.Now.Ticks <= end)
continue;
//Check the currentprincipal. BANG!!!!!!!!!!!!!
var userName = Thread.CurrentPrincipal.Identity.Name;
}
Here's the code that starts the thread
public void Start()
{
Thread thread = new Thread(new ParameterizedThreadStart(ThreadProc));
thread.SetApartmentState(ApartmentState.MTA);
thread.Name = "TestThread";
thread.Start(this);
}
static void ThreadProc(object o)
{
try
{
Builder builder = (Builder)o;
builder.Run();
}
catch (Exception ex)
{
throw;
}
}
So... what am i doing wrong?
Thanks