资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

C#项目中List并发出现数据丢失如何解决-创新互联

C#项目中List并发出现数据丢失如何解决?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:域名申请雅安服务器托管、营销软件、网站建设、运河网站维护、网站推广。
class Program
{
 static List persons;

 static void Main(string[] args)
 {
  persons = new List();

  object sync = new object();

  Parallel.For(0, 1000, (i) =>
  {
   Person person = new Person
   {
    ID = i,
    Name = "name" + i
   };
   lock (sync)
    persons.Add(person);
  });

  Console.WriteLine(persons.Count);
  Console.ReadLine();
 }

 class Person
 {
  public int ID { get; set; }
  public string Name { get; set; }
 }
}

利用安全集合ConcurrentBag取代list

测试程序

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace MyConcurrent
{
  class Program
  {
    /// 
    /// ConcurrentBag并发安全集合
    /// 
    public static void ConcurrentBagWithPallel()
    {
      ConcurrentBag list = new ConcurrentBag();
      Parallel.For(0, 10000, item =>
      {
        list.Add(item);
      });
      Console.WriteLine("ConcurrentBag's count is {0}", list.Count());
      int n = 0;
      foreach (int i in list)
      {
        if (n > 10)
          break;
        n++;
        Console.WriteLine("Item[{0}] = {1}", n, i);
      }
      Console.WriteLine("ConcurrentBag's max item is {0}", list.Max());
    }
    
 
    /// 
    /// 函数入口
    /// 
    /// 
    static void Main(string[] args)
    {
      Console.WriteLine("ConcurrentBagWithPallel is runing" );
      ConcurrentBagWithPallel();
 
      Console.Read();
    }

关于C#项目中List并发出现数据丢失如何解决问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。


网站题目:C#项目中List并发出现数据丢失如何解决-创新互联
网站链接:http://cdkjz.cn/article/csgdic.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220