IConfigurationSectionHandler的线程安全性问题

来源:互联网 发布:php多文件上传原理 编辑:程序博客网 时间:2024/04/30 13:19

class TestMutilThreadSection : IConfigurationSectionHandler
    {
        private IList<string> _list;
        public IList<string> List
        {
            get { return _list; }
        }

        #region IConfigurationSectionHandler Members

        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            _list = new List<string>();
            _list.Add("1");
            Thread.Sleep(2 * 1000);
            _list.Add("2");
            Thread.Sleep(2 * 1000);
            return this;
        }

        #endregion
    }

 

 class Program
    {
        static void Main(string[] args)
        {
            Thread t1 = new Thread(new ThreadStart(AccessSection));
            t1.Start();
            Thread.Sleep(3000);
            Thread t2 = new Thread(new ThreadStart(AccessSection));
            t2.Start();
        }

        static void AccessSection()
        {
            TestMutilThreadSection section = ConfigurationManager.GetSection("TestMutilThreadSection") as TestMutilThreadSection;
            IList<string> list = section.List;
            foreach (string str in list)
                Console.WriteLine(string.Format("ThreadId:{0},{1}", Thread.CurrentThread.ManagedThreadId, str));
        }
    }

运行结果:

 ThreadId:3,1
ThreadId:4,1
ThreadId:4,2
请按任意键继续. . .

 

结论:

TestMutilThreadSection 类在一开始多线程访问的时候,会出现_list字段的线程安全问题。

原创粉丝点击