日期:2014-05-17  浏览次数:20906 次

WCF中静态变量要如何使用才安全?
如 public static IList<DBIDConnStr> listDBIDConnStr = new List<DBIDConnStr>();
------最佳解决方案--------------------
.NET4.0里面有个BlockingCollection<T>类,可以替代List<T>,不过更倾向于使用ConcurrentDictionary<TKey,TValue>,那个可以通过唯一的“键”来达到同步目的,效果更佳。
------其他解决方案--------------------
如果只是初始化一边,后面不再变的话,可以使用Static Contractor:

下面来自msdn: http://msdn.microsoft.com/en-us/library/aa645612.aspx
The static constructor for a class executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

An instance of the class is created.
Any of the static members of the class are referenced.

更多讨论参考:
http://stackoverflow.com/questions/7095/is-the-c-sharp-static-constructor-thread-safe
------其他解决方案--------------------
这篇文章讨论了list<t>的线程安全问题

http://www.cnblogs.com/baihmpgy/archive/2011/07/13/2105018.html
------其他解决方案--------------------
你的使用场景描述下把
可以用缓存不?
------其他解决方案--------------------
listDBIDConnStr这个是保存连接字符串的list,没有会加载一次,如果存在直接从这个对象中查询处理,使用basicHttpBinding,

#region DB ConnStr
        /// <summary>
        /// connection string list
        /// </summary>
        public static IList<DBIDConnStr> listDBIDConnStr = new List<DBIDConnStr>();

        /// <summary>
        /// load connection string
        /// </summary>
        private static void DefineConnStr(DBID dbID)
        {
            bool bConnSucceed = false;
            string connStrTmp = string.Empty;
            string path = AppDomain.CurrentDomain.BaseDirectory;
            if (!path.EndsWith("\\"))
                path += "\\";
            //read xml     
            XmlDocument xDoc = new XmlDocument();
            
            try
            {
                xDoc.Load(path + "Config.xml");
            }
            catch (Exc