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;
}
}
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;
}
}
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.
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.