thread safety / static method

P

Peter K

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
 
M

Marc Gravell

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
 
J

Jon Skeet [C# MVP]

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top