的Parallel.For失败(C#) [英] Parallel.For fail (C#)

查看:200
本文介绍了的Parallel.For失败(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一些代码:

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>(); 
            }
        }
    }



但结果没有预期(

but results are not expected(

Console.WriteLine调用之前,并非所有的周期完成

Not all of the cycles are finished before Console.WriteLine calls

什么是使用并行的问题。对于?

What is the problem with using Parallel.For?

推荐答案

您正在运行到什么叫做的竞争条件,由于列表集合在.NET是不是线程安全的,这是如添加()不是原子操作基本上调用Add()方法在一个线程可以破坏另一个线程的Add()完成之前,你需要为你的代码是线程安全的并发收集。

You're running into what's known as a Race Condition. Since the List collection in .Net isn't thread safe, it's operations such as Add() aren't atomic. Basically a call to Add() on one thread can destroy another thread's Add() before it is complete. You need a thread-safe concurrent collection for your code.

试试这个:使用System.Threading.Tasks

Try this:

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是最接近一个线程安全的列表。只要记住,因为我们正在处理的未知调度,整数不会为了。

The ConcurrentBag is the closest thing to a thread-safe list. Just remember since we are dealing with unknown scheduling, the integers won't be in order.

这篇关于的Parallel.For失败(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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