views:

71

answers:

2

Do I need locking for _userByNameQuery static field Yes/No and way?

public class SomeClass 
{
    static Func<Entities, string, IQueryable<User>> _userByNameQuery = 
        CompiledQuery.Compile<Entities, string, IQueryable<User>>
            ((context, userName) =>
                context.Users.Where(u => u.UserName.ToUpper() == userName));

    public bool UserNameExists(string userName)
    {
        userName = userName.ToUpper();
        return _userByNameQuery.Invoke(DataContext, userName).Count() > 0;
    }
}
+3  A: 

Make it readonly, and you don't. It will be initialized just once at part of type initialization, and delegates are immutable. No problem.

Jon Skeet
+1  A: 

It is standard practice to make static members thread-safe. The reason is because you cannot control which threads are accessing static members like you can for instance members. However, this does not mean that you have to use locks. Like Jon said, if you make sure that the field can never change and that instance referenced by that field is immutable then you have nothing to worry about. There would be no need for a lock.

Brian Gideon
Thank you for your explanations.
Darius Kucinskas