C# List 并發(fā)丟數(shù)據(jù)問題原因及解決方案
項(xiàng)目中出了個(gè) BUG,就在我眼皮子底下,很明顯的一個(gè) BUG,愣是看了兩天才看出來。
我有多個(gè)任務(wù)并發(fā),任務(wù)執(zhí)行完成后都有一個(gè)返回結(jié)果,我用一個(gè) List
將結(jié)果收集起來,等所有任務(wù)完成后,發(fā)送出去。結(jié)果一直 丟數(shù)據(jù)。
我反復(fù)檢查邏輯都沒有問題,最后恍然 List
是非線程安全的。
大家都知道 List
是非線程安全的,但是如果僅有 Add
操作呢?估計(jì)有些人就會(huì)認(rèn)為沒問題。
下面的代碼,期望輸出的結(jié)果是 1000,然而,注釋掉 lock
后,結(jié)果就不一樣了。
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
測(cè)試程序
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并發(fā)安全集合 /// </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> /// 函數(shù)入口 /// </summary> /// <param name="args"></param> static void Main(string[] args) { Console.WriteLine("ConcurrentBagWithPallel is runing" ); ConcurrentBagWithPallel(); Console.Read(); }
以上就是C# List 并發(fā)丟數(shù)據(jù)問題原因及解決方案的詳細(xì)內(nèi)容,更多關(guān)于C# List 并發(fā)丟數(shù)據(jù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用C#獲取遠(yuǎn)程圖片 Form用戶名與密碼Authorization認(rèn)證的實(shí)現(xiàn)
本篇文章介紹了,使用C#獲取遠(yuǎn)程圖片 Form用戶名與密碼Authorization認(rèn)證的實(shí)現(xiàn)。需要的朋友參考下2013-04-04Unity3D實(shí)現(xiàn)自動(dòng)尋路
這篇文章主要為大家詳細(xì)介紹了Unity3D實(shí)現(xiàn)自動(dòng)尋路,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-07-07C#解碼base64編碼二進(jìn)制數(shù)據(jù)的方法
這篇文章主要介紹了C#解碼base64編碼二進(jìn)制數(shù)據(jù)的方法,涉及C#中Convert類的靜態(tài)方法Convert.FromBase64String使用技巧,需要的朋友可以參考下2015-04-04C#中GraphicsPath的Widen方法用法實(shí)例
這篇文章主要介紹了C#中GraphicsPath的Widen方法用法,實(shí)例分析了Widen方法的使用技巧,需要的朋友可以參考下2015-06-06