thread safety / static method
- From: Peter K <xdzgor@xxxxxxxxxxx>
- Date: Wed, 19 Dec 2007 01:14:14 -0800
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
.
- Follow-Ups:
- Re: thread safety / static method
- From: Jon Skeet [C# MVP]
- Re: thread safety / static method
- From: Marc Gravell
- Re: thread safety / static method
- Prev by Date: Re: C# Windows service hangs
- Next by Date: Oracle Data Provider Issue
- Previous by thread: call procedure (schedule)
- Next by thread: Re: thread safety / static method
- Index(es):