c# - Parallel.For 失败 (C#)

标签 c# parallel-processing

我写了一些代码:

class Program
    {
        public const int count = 3000;
        static List<int> list = new List<int>();
        static void DoWork(int i)
        {            
            list.Add(i);
        }        
        static void Main(string[] args)
        {
            while (true)
            {

                Stopwatch s = new Stopwatch();
                s.Start();
                Parallel.For(0, count + 1, DoWork);            
                s.Stop();
                Console.WriteLine("\n Elapsed: " + s.Elapsed.ToString());
                Console.WriteLine("Expected: {0}", count + 1);
                Console.WriteLine("count: {0}", list.Count);
                Console.ReadKey();
                list = new List<int>(); 
            }
        }
    }

但结果不是预期的(

并非所有循环都在 Console.WriteLine 调用之前完成

使用 Parallel.For 有什么问题?

最佳答案

您遇到了所谓的 Race Condition .由于 .Net 中的 List 集合不是线程安全的,因此 Add() 等操作不是原子的。基本上,在一个线程上调用 Add() 可以在完成之前破坏另一个线程的 Add() 。您的代码需要一个线程安全的并发集合。

试试这个:

using System.Threading.Tasks;
class Program
{

    public const int count = 3000;
    static ConcurrentBag<int> bag = new ConcurrentBag<int>();
    static void DoWork(int i)
    {
        bag.Add(i);
    }
    static void Main(string[] args)
    {
        while (true)
        {

            Stopwatch s = new Stopwatch();
            s.Start();
            Parallel.For(0, count + 1, DoWork);
            s.Stop();
            Console.WriteLine("\n Elapsed: " + s.Elapsed.ToString());
            Console.WriteLine("Expected: {0}", count + 1);
            Console.WriteLine("count: {0}", bag.Count);
            Console.ReadKey();
            bag = new ConcurrentBag<int>();
        }
    }
}

ConcurrentBag 是最接近线程安全列表的东西。请记住,由于我们正在处理未知的调度,因此整数不会按顺序排列。

关于c# - Parallel.For 失败 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6396256/

相关文章:

java - 集群java独立应用程序

c# - 更改 IdentityServer.v3 中的嵌入式自签名 X.509 证书 (idsrv3test.pfx)

c# - 抑制 TryParse 调用的静态代码分析警告 CA1806

c# - 为什么不能转换此double值

c# - 在 C# 中打开声音控制 (OSC)

r - 在 Shiny 中使用并行包

unit-testing - 编写并行单元测试的最佳实践

使用 OpenMP 进行 Cholesky 分解

c# - 如何将 SQL Server 与 .NET MAUI 连接

python - 即使已安装,“导入 future ”也不起作用