A single context with many threads with the Entity Framework

I have the following:

           await Task.WhenAll(
                 Task.Run(() => HandleJob("one"),
                 Task.Run(() => HandleJob("two"),
                 Task.Run(() => HandleJob("three"));

Where is HandleJob:

       private async Task HandleJob(string param) {
              using (var db = new DbContext()) {
                     _numberService = new NumberService(db);
                     _numberService.DoThis(param);
              }
       }

And NumberService is:

    public class NumberService {

           private readonly DbContext db;

           private CommService _commService;

           public NumberService(DbContext db) {
              this.db = db;
              _commService = new CommService(db);
           }


           public void DoThis(string param){
              _commService.DoThat(param);   
           }

     }

And CommService is:

     public class CommService {

           private readonly DbContext db;

           public CommService(DbContext db) {
              this.db = db;
           }

           public void DoThat(string param){
              db.Things.Add(param);
              db.SaveChanges();
           }

     }

I am having a problem when I see the following when I try to run this:

An exception of type System.InvalidOperationException occurred in EntityFramework.dll, but was not processed in the user code. Context cannot be used during model creation. This exception can be if the context is used inside the OnModelCreating method or if several threads access the same context instance. Note that the members of the DbContext instance and its associated classes do not guarantee thread safety.

What am I doing wrong? I thought that using a new one dbContextfor each thread, I would be fine.

+4
1

. , _numberService async, async . Doh.

0

Source: https://habr.com/ru/post/1569572/


All Articles