C# List 并发丢数据问题原因及解决方案
项目中出了个BUG,就在我眼皮子底下,很明显的一个BUG,愣是看了两天才看出来。
我有多个任务并发,任务执行完成后都有一个返回结果,我用一个List将结果收集起来,等所有任务完成后,发送出去。结果一直丢数据。
我反复检查逻辑都没有问题,最后恍然List是非线程安全的。
大家都知道List是非线程安全的,但是如果仅有Add操作呢?估计有些人就会认为没问题。
下面的代码,期望输出的结果是1000,然而,注释掉lock后,结果就不一样了。
classProgram
{
staticListpersons;
staticvoidMain(string[]args)
{
persons=newList();
objectsync=newobject();
Parallel.For(0,1000,(i)=>
{
Personperson=newPerson
{
ID=i,
Name="name"+i
};
lock(sync)
persons.Add(person);
});
Console.WriteLine(persons.Count);
Console.ReadLine();
}
classPerson
{
publicintID{get;set;}
publicstringName{get;set;}
}
}
利用安全集合ConcurrentBag取代list
测试程序
usingSystem;
usingSystem.Collections.Concurrent;
usingSystem.Collections.Generic;
usingSystem.Diagnostics;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceMyConcurrent
{
classProgram
{
///
///ConcurrentBag并发安全集合
///
publicstaticvoidConcurrentBagWithPallel()
{
ConcurrentBaglist=newConcurrentBag();
Parallel.For(0,10000,item=>
{
list.Add(item);
});
Console.WriteLine("ConcurrentBag'scountis{0}",list.Count());
intn=0;
foreach(intiinlist)
{
if(n>10)
break;
n++;
Console.WriteLine("Item[{0}]={1}",n,i);
}
Console.WriteLine("ConcurrentBag'smaxitemis{0}",list.Max());
}
///
///函数入口
///
///
staticvoidMain(string[]args)
{
Console.WriteLine("ConcurrentBagWithPallelisruning");
ConcurrentBagWithPallel();
Console.Read();
}
以上就是C#List并发丢数据问题原因及解决方案的详细内容,更多关于C#List并发丢数据的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。