C# Parallel ConcurrentBag

using System.Collections.Concurrent;
using System.Diagnostics;

namespace ConsoleApp85
{
    internal class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Stopwatch watch = new Stopwatch();
                Console.WriteLine("AddModelSequential started!");                
                watch.Start();
                AddModelSequential(10000000);
                watch.Stop();
                Console.Error.WriteLine($"AddModelSequential cost:{watch.ElapsedMilliseconds} milliseconds!\n\n\n");

                 

                Console.Error.WriteLine("AddModelParallel() started!");
                watch.Restart();
                AddModelParallel(10000000);
                watch.Stop();
                Console.Error.WriteLine($"AddModelParallel() cost {watch.ElapsedMilliseconds} milliseconds!");
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                Console.Error.WriteLine(ex.StackTrace.ToString());
            }
           
            Console.ReadLine();
        }

        static List<dynamic> AddModelSequential(int modelsCount)
        {
            var list=new List<dynamic>();
            for(int i=0;i<modelsCount;i++)
            {
                int f = 0;
                for (int j = 0; j < 5000; j++)
                {
                    f++;
                }
                list.Add(new
                {
                    bbb = i,
                    aaa = "1",
                    ccc = f
                });
            }
            return list;
        }

        static ConcurrentBag<dynamic> AddModelParallel(int modelsCount)
        {
            var list=new ConcurrentBag<dynamic>();
            Parallel.For(0, modelsCount, x =>
            {
                int f = 0;
                for(int j=0;j<5000;j++)
                {
                    f++;
                }
                list.Add(new
                {
                    bbb = x,
                    aaa = "a",
                    ccc = f
                });
            });
            return list;
        }
    }
}

 

 

 

 

posted @ 2024-09-26 22:17  FredGrit  阅读(2)  评论(0编辑  收藏  举报