Hi, I am worried about thread-safety in the following code.
If two threads call GetObject() is it possible they both create a new
AlphaContext object and add it to HttpContext.Items?
Can I avoid this with a lock? (I assum I would need a "static" object to
lock on?)
public class ContextFactory
{
private const string OBJECT_KEY = "AlphaSContext";
private ContextFactory()
{
}
public static IContext GetObject()
{
HttpContext httpContext = HttpContext.Current;
IContext context = null;
if (httpContext.Items.Contains(OBJECT_KEY))
{
context = (IContext)httpContext.Items[OBJECT_KEY];
}
else
{
context = new AlphaContext();
httpContext.Items.Add(OBJECT_KEY, context);
}
return (IContext)context;
}
}
Thanks, Peter
Marc Gravell - 19 Dec 2007 09:26 GMT
> If two threads call GetObject() is it possible they both create a new
> AlphaContext object and add it to HttpContext.Items?
If the two threads are executing in the same http-context, then yes
this is a possibility. HttpContext.Current returns the http-context
for the current thread - it isn't a single static value so you don't
need to worry about *all* threads; just those that you have created
(directly or indirectly) relating to the same http-context.
I don't know what the AlphaContext represents here (and what the cost
of the object is), but a pragmatic option might be to simply ensure
there is a valid context before you start spawning threads?
A static lock would have the side-effect of serializing *all* threads
- not just those relating to the same http-context; I would be
cautious about locking on the httpContext itself, though, simply
because you don't know what else might be locking on it.
Marc
Jon Skeet [C# MVP] - 19 Dec 2007 09:27 GMT
> Hi, I am worried about thread-safety in the following code.
> If two threads call GetObject() is it possible they both create a new
> AlphaContext object and add it to HttpContext.Items?
It would only be an issue if two threads were using the same
HttpContext.
While that's possible, it's unlikely - and you should know about it if
your code might execute in that fashion.
Jon