views:

84

answers:

2

Do I have to lock access to instance members?

Example:

public class HttpModule : IHttpModule
{
    //...

    Dictionary<int, int> foo;

    void UseFoo(int a, int b)
    {
        foo[a] = b;
    }
}
+3  A: 

It's not crystal clear to me so far from the MSDN documentation, but I found a forum post from someone who claims to know the answer. It sounds like you shouldn't expect bad stuff to happen with your implementation, but you should be aware that foo's state will not necessarily be shared across all results since your HttpModule will be created once per HttpApplication that IIS chooses to keep in its pool.

sblom
Yes, it reuses the instance among many different requests. But the question is whether it reuses the instance among different threads.
TN
From what I can tell: Yes, but not at the same time. An HttpApplication seems to be assigned to a given request for the duration of that request.
sblom
Ok, thank you. I will wait until someone how knows that exactly confirm this, since I will use that code in production environment, and I will be hard to debug.
TN
+1  A: 

I recently found an article which touches on this question slightly: http://www.dominicpettifer.co.uk/Blog/41/ihttpmodule-gotchas---the-init---method-can-get-called-multiple-times

It doesn't mention threads, but only says that the worker process will

instantiate as many HttpApplication objects as it thinks it needs, then it'll pool them for performance reasons, reusing instances as new requests come in before sending them back into the pool.

Following the code in from the link, you can be sure that your init code is executed once in a thread-safe manner:

private static bool HasAppStarted = false; 
private readonly static object _syncObject = new object(); 

public void Init(HttpApplication context) 
{ 
    if (!HasAppStarted) 
    { 
        lock (_syncObject) 
        { 
            if (!HasAppStarted) 
            { 
                // Run application StartUp code here 

                HasAppStarted = true; 
            } 
        } 
    } 
}

I've been meaning to set up a test app to run this and test it, just to see if it's true, but I haven't had the time.

Jim Schubert
Thank you for your answer. This checks whether it is shared now. I need to know it exactly, since as I metioned above I will use that in production environment and it will be really painful if it is changed, for instance during some update of .NET Framework or IIS.
TN