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; }
}
}
测试程序
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并发出现数据丢失如何解决问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。