问题描述
我在MSDN中读到,List用作公共静态类型时是线程安全的.但是,以下代码段证明不是这样.我正在尝试从列表中添加和删除元素,但是remove方法在途中抛出一个错误,说索引超出范围.这里出了什么问题?
I was reading in MSDN that a List is thread safe when used as a public static type . However the following code snippet proves otherwise. I am trying to add and remove elements from the list but the remove method throws an error midway saying index out of bounds. What is going wrong here?
这是检查我的理论的正确实现.如果不是这样,有人可以提出一个更好的例子吗?
Is this a right implementation to check my theory. If not, can someone please suggest a better example.
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();
}
}
推荐答案
该说法不正确.您可能是指此文本:
That statement is not true. You probably are referring to this text:
是指类List<T>
的成员.它确实不引用类List<T>
的实例.
That refers to members of the class List<T>
. It does not refer to instances of the class List<T>
.
这篇关于不是线程安全的-公共静态List< T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!