> This way accessing _userService will be thread safe but calling > LoadCurrentUser will not; that method could actually be executed by > multiple threads in parallel thus breaking the thread safety. > Imho using a synchronization object would do the trick and make that > method really thread safe. > > Frans, what do you think?
Every thread creates its own stackframe when it enters a routine, like LoadCurrentUser. This means that every local variable created (or temp variable like a result from a method which is passed on to another method) is placed in that stackframe of the thread. As it is an ASP.NET application, what's often confused is request-safe with thread-safe. ASP.NET can switch threads for a single request under high load (to prevent slow, heavy requests starve small ones). So this routine's code has for example: HttpContext.Current.User, which is request safe and thread safe by default. It then pulls a value from the service. This value is stored in the thread's local stackframe, so every thread has a different instance of that value. It then returns that value, so it's perfectly threadsafe. In general you can spot thread unsafety easily by looking at access to static members. Any static member is a target for thread unsafety if it's accessed by static code. FB > > -- > Efran Cobisi > http://www.cobisi.com > > Frans Bouma wrote: > > no. You should do: > > private static IUserService _userService = > > ContainerWebAccessorUtil.Container.Resolve<IUserService>(); > > > > public static SiteUser LoadCurrentUser() > > { > > if ((HttpContext.Current.User == null) || > > (!HttpContext.Current.User.Identity.IsAuthenticated)) > > throw new Exception("User is not authenticated."); > > return _userService.GetSiteUserByUid(new > > Guid(HttpContext.Current.User.Identity.Name)); > > } > > > > i.o.w.: initialize the singleton in the static declaration, > otherwise > > it's not threadsafe. Please see the excellent articles about this by Jon > > Skeet: > > http://www.yoda.arachsys.com/csharp/singleton.html > > =================================== > This list is hosted by DevelopMentorR http://www.develop.com > > View archives and manage your subscription(s) at http://discuss.develop.com =================================== This list is hosted by DevelopMentorĀ® http://www.develop.com View archives and manage your subscription(s) at http://discuss.develop.com