Wednesday 15 May 2013

Locking thread singleton example

Example of implementing singleton.


 public class Settings
    {
        /// <summary>
        /// Private lock used while loading
        /// </summary>
        private Object setupLock = new Object();

        /// <summary>
        /// Container for settings loaded from web.config.
        /// </summary>
        private Dictionary<string, object> _settings { get; set; }

        /// <summary>
        /// While class is getting loading information from app.config, the object is locked.
        /// </summary>
        public Settings()
        {
            // Check if settings is null, othewise do not carry on with constructing settings.
            if (_settings == null)
            {
                // Add lock on the process inside
                lock (setupLock)
                {
                    // if this has been hit by 2 processes after each other, make sure that the value is still before start processing.
                    if (_settings == null)
                    {
                        var settings = new Dictionary<string, object>();
                        foreach (var key in ConfigurationManager.AppSettings.AllKeys)
                        {
                            settings.Add(key, ConfigurationManager.AppSettings[key].ToString(CultureInfo.InvariantCulture));
                        }
                        _settings = settings;
                    }
                }
            }
        }

    }
}

No comments:

Post a Comment