Hosea146
Hosea146

Reputation: 7702

C# - Static property in class

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?

Upvotes: 3

Views: 414

Answers (4)

Marc Gravell
Marc Gravell

Reputation: 1062502

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).

Upvotes: 1

Mario Vernari
Mario Vernari

Reputation: 7304

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.

Upvotes: 0

Oleg Dudnyk
Oleg Dudnyk

Reputation: 1009

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.

Upvotes: 0

Jalal Said
Jalal Said

Reputation: 16162

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.

Upvotes: 1

Related Questions