C#项目中List并发出现数据丢失如何解决?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
class Program{ static List<Person> persons; static void Main(string[] args) { persons = new List<Person>(); 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 { /// <summary> /// ConcurrentBag并发安全集合 /// </summary> public static void ConcurrentBagWithPallel() { ConcurrentBag<int> list = new ConcurrentBag<int>(); 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()); } /// <summary> /// 函数入口 /// </summary> /// <param name="args"></param> static void Main(string[] args) { Console.WriteLine("ConcurrentBagWithPallel is runing" ); ConcurrentBagWithPallel(); Console.Read(); }
关于C#项目中List并发出现数据丢失如何解决问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注编程网行业资讯频道了解更多相关知识。