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

前端之家收集整理的这篇文章主要介绍了c# – 两个或多个线程可以在同一个列表中迭代,没有任何问题?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
谈论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.

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

猜你在找的C#相关文章