快速阅读
Parallel不能保证线程安全的,他操作的集合要把集合先变更为线程安全的集合,这样才能保证在并行循环的过程中,线程之间不会互相产生干扰,而导致计算结果不正确,
比如说下面这一个例子。S如果我们不用现成安全的集合去运行那么嗯显示的结果将不会是我们想要的结果,我们需要把集合先变成安全的现场集合才可以去调用,才能获得我们需要的正确结果,线程安全的集合包含有concurrent dictionary,concurrent query等类型。
static void Main(string[] args)

   {
       //List<Product> products = new List<Product>();
       ConcurrentQueue<Product> products = new ConcurrentQueue<Product>();
       Parallel.For((long) 0, 1000000, (i) =>
       {
           Product product = new Product();
           product.Name = "name" + i;
           product.Category = "Category" + i;
           product.SellPrice = (int) i;
           products.Enqueue(product);
       });
       Console.WriteLine(products.Count);
       Console.ReadLine();
   }
   // Define other methods and classes here
   class Product
   {
       public string Name { get; set; }
       public string Category { get; set; }
       public int SellPrice { get; set; }
   }

}
还有一种说法是他说那个拍出来,嗯,加了一个索引这样不会造成这样也能保证现场安全
嗯,过两天可以用代码来验证一下试试。
Parallel.For(0, 5, t =>
{

this.DoSomethingLong($"btnParallel_Click_00{t}");

});
可以定义一个派出来option,来在里面设定开启的最大线程数。
ParallelOptions options = new ParallelOptions()
{

 MaxDegreeOfParallelism = 3   //最大3个线程并发任务

};
Parallel.ForEach(new int[] { 0, 1, 2, 3, 4 }, options, t =>
{

this.DoSomethingLong($"btnParallel_Click_00{t}");

本文由 hcb 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论