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:
That refers to members of the class
List<T>. It does not refer to instances of the classList<T>.