您的位置:首页 > 其它

IConfigurationSectionHandler的线程安全性问题

2009-11-27 14:44 405 查看
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字段的线程安全问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: