1

I am using the Entity Framework and Linq technology but when I tried to use parallel.For it happens I have an Exception

This is my attempt

 class Program
{
    static void Main(string[] args)
    {
        DbContextClass db = new DbContextClass();

                Parallel.For(0, 10, i =>
                {
                    Category ct = new Category
                    {
                        NameCategory = "SomeText"                           
                    };
                    db.Categories.Add(ct);
                });                           

             db.SaveChanges();
            Console.ReadKey();
    }
}

1 Answers1

1

Check ths github issue here

Work on the assumption that none of the code is thread safe. All of the main APIs, like DbContext, DbSet, etc. are not thread safe. There are some thread safe parts, which are usually singleton or similar shared services, but almost all of that is internal.

This does not mean that you can't work in paraller with the same DBContext. Just change your code to the following (creating a new DBContext each time):

class Program
{
    static void Main(string[] args)
    {
       Parallel.For(0, 10, i =>
       {
          using(DbContextClass db = new DbContextClass()) {
               Category ct = new Category
               {
                    NameCategory = "SomeText"                           
               };
               db.Categories.Add(ct);
               db.SaveChanges();
          }
      });                           

      Console.ReadKey();
    }
}
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61