SoFunction
Updated on 2025-03-06

C# List Concurrent data loss problem and solution

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 oneListCollect 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 knowsListIt is non-thread-safe, but if onlyAddWhat about the operation? I guess some people will think it's okay.

The following code expects the output to be 1000, however, comment outlockAfter 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
  {
    /// &lt;summary&gt;
    /// ConcurrentBag concurrent secure collection    /// &lt;/summary&gt;
    public static void ConcurrentBagWithPallel()
    {
      ConcurrentBag&lt;int&gt; list = new ConcurrentBag&lt;int&gt;();
      (0, 10000, item =&gt;
      {
        (item);
      });
      ("ConcurrentBag's count is {0}", ());
      int n = 0;
      foreach (int i in list)
      {
        if (n &gt; 10)
          break;
        n++;
        ("Item[{0}] = {1}", n, i);
      }
      ("ConcurrentBag's max item is {0}", ());
    }
    
 
    /// &lt;summary&gt;
    /// Function entry    /// &lt;/summary&gt;
    /// &lt;param name="args"&gt;&lt;/param&gt;
    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!