小编cri*_*rip的帖子

.ToList()线程安全

我有以下情况:

  • 只有一个thead仅将项目添加到列表中
  • 多个线程可以读取项目。

我知道当我们直接公开列表时,我会在枚举时遇到并发修改。

但是,当我调用.ToList()它时,它成为List的一个实例,并使用.NET Framework的Array.Copy函数复制所有项目。

您的意思是,如果脏读没问题,使用这种方法是否安全?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var container = new Container();
            Thread writer = new Thread(() =>
            {
                for (int i = 0; i < 1000; i++)
                {
                    container.Add(new Item("Item " + i));
                }
            });

            writer.Start();

            Thread[] readerThreads = new Thread[10];
            for (int i = 0; i < readerThreads.Length; i++)
            {
                readerThreads[i] = new Thread(() =>
                {
                    foreach …
Run Code Online (Sandbox Code Playgroud)

.net c# multithreading thread-safety

5
推荐指数
1
解决办法
3662
查看次数

标签 统计

.net ×1

c# ×1

multithreading ×1

thread-safety ×1