不是线程安全的-公共静态List< T> [英] Not thread safe - public static List<T>

查看:78
本文介绍了不是线程安全的-公共静态List< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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();


    }

}

推荐答案

我在MSDN中读到一个List用作公共静态类型时是线程安全的.

I was reading in MSDN that a List is thread safe when used as a public static type.

该说法不正确.您可能是指此文本:

That statement is not true. You probably are referring to this text:

这种公共静态成员是线程安全的.

Public static members of this type are thread safe.

是指类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&lt; T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆