There was a bug in the project, just under my nose, and there was a very obvious bug. I watched it for two days before I could see it.
I have multiple tasks concurrently, and after the task is executed, one returns the result, I use oneList
Collect the results and send them out after all tasks are completed. As a result, data is lost.
I checked the logic repeatedly and there was no problem, and finally I suddenly realized List
It is non-thread-safe.
Everyone knowsList
It is non-thread-safe, but if onlyAdd
What about the operation? I guess some people will think it's okay.
The following code expects the output to be 1000, however, comment outlock
After that, the result is different.
class Program { static List<Person> persons; static void Main(string[] args) { persons = new List<Person>(); object sync = new object(); (0, 1000, (i) => { Person person = new Person { ID = i, Name = "name" + i }; lock (sync) (person); }); (); (); } class Person { public int ID { get; set; } public string Name { get; set; } } }
Replace list with secure collection ConcurrentBag
Testing procedures
using System; using ; using ; using ; using ; using ; using ; namespace MyConcurrent { class Program { /// <summary> /// ConcurrentBag concurrent secure collection /// </summary> public static void ConcurrentBagWithPallel() { ConcurrentBag<int> list = new ConcurrentBag<int>(); (0, 10000, item => { (item); }); ("ConcurrentBag's count is {0}", ()); int n = 0; foreach (int i in list) { if (n > 10) break; n++; ("Item[{0}] = {1}", n, i); } ("ConcurrentBag's max item is {0}", ()); } /// <summary> /// Function entry /// </summary> /// <param name="args"></param> static void Main(string[] args) { ("ConcurrentBagWithPallel is runing" ); ConcurrentBagWithPallel(); (); }
The above is the detailed content of the cause and solution of the concurrent data loss problem of C# List. For more information about the concurrent data loss of C# List, please pay attention to my other related articles!