views:

43

answers:

1

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

+1  A: 

If you start a new Thread it won't use the same HttpContext (it will run on another context).

What you can do is pass the HttpContext.Current to that method. Why are you passing "this"?

Take a look here... http://msdn.microsoft.com/en-us/library/system.threading.parameterizedthreadstart.aspx

Your DoWork will receive an object (that will be your HttpContext.Current)

Also, to wait 3 seconds you can always do a

Thread.Sleep(3000); - miliseconds.

It's better than that while loop you have there... Less code, right? :)

Flavio
Thanks for the explanation
vIceBerg