3

I have the following code:

    internal class ModuleLogic
    {
        #region [Private Variables]
        private static ReaderWriterLockSlim _moduleListLock = new ReaderWriterLockSlim();
        private static List<Module> _moduleList;
        #endregion   

        public static void RefreshModuleData()
        {
            _moduleListLock.EnterWriteLock();
            try
            {
                ModuleData.RefreshModuleData(_moduleList);
            }
            finally
            {
                _moduleListLock.ExitWriteLock();
            }
        }
   }

Am I correct that each time the RefreshModuleData() method is accessed, the two private static variables are shared for each access?

4 Answers 4

1

I correct that each time this class is instantiated, the two private static variables are only instantiated once (the first time) and used for each instance

Yes, Since they are static fields, they only will be instantiated just ones. that is of course if you didn't override them any place in the code.

Sign up to request clarification or add additional context in comments.

Comments

1

The static fields are indeed shared between all calls. To avoid confusion you could also make the lock field "readonly". The list field probably can't be readonly, but note that it would be a bad idea for you to ever change the contents in the list (once available in the field) since it could be in use by multiple threads.

Note: since it looks like you currently do update the list, there is a chance that your current code is not thread safe (if any callers look at the list outside of a locked region - a "read" lock would do).

As a minor note, a "lock" would have less overhead there, and the same call pattern (since you always take a write lock).

1 Comment

Thanks very much. I actually have additional code that will read this list on separate threads, so I will be using EnterReadLock's for those. I don't want readers to block each other, but they need to wait on writes to the list.
0

Your static property _moduleListLock is initialized only once just in place where it is declared. Howewer every Application Domain could have its own copy of static variables.

Comments

0

The very first time you refer anything of the ModuleLogic class, its static constructor (where defined) and all of the static fields are initialized, in a top-to-bottom order. Being "static" there's only one reference in the whole application.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.