加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 两个或多个线程可以在同一个列表中迭代,没有任何问题?

发布时间:2020-12-15 17:42:21 所属栏目:百科 来源:网络整理
导读:谈论System.Collections.Generic.List T这里. 下面的例子可以方法1和方法2执行同一时间,在不同的线程上没有任何问题? 谢谢 class Test{ private readonly ListMyData _data; public Test() { _data = LoadData(); } private ListMyData LoadData() { //Get
谈论System.Collections.Generic.List< T>这里.

下面的例子可以方法1和方法2执行同一时间,在不同的线程上没有任何问题?

谢谢

class Test
{
    private readonly List<MyData> _data;

    public Test()
    {
        _data = LoadData();
    }

    private List<MyData> LoadData()
    {
        //Get data from dv.
    }

    public void Method1()
    {
        foreach (var list in _data)
        {
            //do something
        }
    }

    public void Method2()
    {
        foreach (var list in _data)
        {
            //do something
        }
    }
}

解决方法

是,列表< T>只要没有线程修改列表,就可以安全地从多个线程中读取.

从the docs:

A List<T> can support multiple
readers concurrently,as long as the
collection is not modified.
Enumerating through a collection is
intrinsically not a thread-safe
procedure. In the rare case where an
enumeration contends with one or more
write accesses,the only way to ensure
thread safety is to lock the
collection during the entire
enumeration. To allow the collection
to be accessed by multiple threads for
reading and writing,you must
implement your own synchronization.

(关于重复“本质上不是一个线程安全的过程”的观点是针对其他突变列表的).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读