【发布时间】:2011-11-20 04:53:48
【问题描述】:
我在 MSDN 中读到 List 在用作公共静态类型时是线程安全的。但是,以下代码 sn-p 证明并非如此。我正在尝试从列表中添加和删除元素,但是 remove 方法在中途抛出一个错误,说索引超出范围。这里出了什么问题?
这是检查我的理论的正确实现吗?如果没有,有人可以推荐一个更好的例子。
class Program
{
public static List<string> strlist = new List<string>();
public static AutoResetEvent autoEvent = new AutoResetEvent(false);
static void Main(string[] args)
{
strlist = new List<string>();
new Thread(() =>
{
for(int i=0;i<10000000;i++)
{
strlist.Add("item1");
}
//Thread.Sleep(5000);
autoEvent.Set();
}).Start(); ;
new Thread(() => {
strlist.ForEach(e => strlist.Remove(e));
}).Start();
Console.WriteLine("Waiting");
autoEvent.WaitOne();
int ci = 0;
strlist.ForEach(str => ci++);
Console.WriteLine(ci.ToString() + " Done");
Console.Read();
}
}
【问题讨论】:
-
“我在 MSDN 中读到 List 在用作公共静态类型时是线程安全的。”这不是真的。列表的 创建 是线程安全的,但访问它不是(如您的代码所示)。
-
请链接到此文档。我可以在
List<T>的文档中看到以下内容:Public static (Shared in Visual Basic) members of this type are thread safe.。这与您的断言非常不同。 -
你读错了。见马克的回答。再次查看文档。
标签: c# multithreading thread-safety