Link to home
Start Free TrialLog in
Avatar of aspnetdev
aspnetdev

asked on

Using Lock in c#

Hi,
I have to use Lock in my code,this is the first time im using the locking.And my understanding is that lock should be implemented only at some critical parts of the code.I used the lock in my function as follows :
in the code snippet ..also i declared it as private static.Is this the way to do it?
public string Get(string Key)
        {
            lock (thisLock)
            {
                if (Pairs.ContainsKey(Key))
                {
                    return Pairs[Key].ToString();
                }
                else
                {
                    // if in the file load and return else initialize and return
 
 
                    Configuration cm = ConfigurationManager.OpenExeConfiguration(path);
                    string value = "";
 
                    try
                    {
 
                        KeyValueConfigurationElement kv = cm.AppSettings.Settings[Key];
                        if (kv != null)
                        {
                            value = kv.Value;
                        }
                        else
                        {
                            Set(Key, value);
                        }
                        return value;
                    }
                    catch { value = ""; }
                    Set(Key, value);
                    return value;
 
                }
            }
        }

Open in new window

Avatar of p_davis
p_davis

in theory you should use lock on whatever element you don't want another thread to access until the processing is done from a previous thread.

Avatar of aspnetdev

ASKER

but i can use the lock in a class as many times i want...right?and on as many functions i want..?
ASKER CERTIFIED SOLUTION
Avatar of p_davis
p_davis

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
correct
what did you declared as private static. i don't see it?

Also, lock is used when,
multiple threads are accessing same object.

You don't need lock if
application is single threaded or
no thread shares a common object
Lock will be used when same object is going to be shared by different thread and you want only one thread  to do the operations on that object.
Example scenarios-
Suppose you are having a application where a change in profile of a user can trigger the change in the profile of other users. So then you will like to put a lock over this operation as you will like only one thread at a moment to perform the action.