简体   繁体   中英

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?

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.

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM