简体   繁体   中英

Entity Framework Core and multithreading

In my ASP.NET Core application, I have some complex business logic involving multiple threads doing database operations outside the scope of an HTTP request. Accessing the database from the same thread processing the request is trivial, but when spawning threads that requires their own DbContext, this turns out to be tedious. As the DbContext itself is not thread-safe, I have tried to create a new DbContext together with its options in addition to obtaining a DbContext from an IServiceProvider. With both approaches, I get the following exception:

An attempt was made to use the context while it is being configured. A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point.

I'm getting the impression that I'm approaching this problem the wrong way and that I'm not supposed to handle database connections like this. How am I then supposed to obtain a DbContext in a separate thread from the one processing incoming requests?

I tested and it works:

var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
                            optionsBuilder.UseSqlServer(DbConnectionString);

                            using (var context = new ApplicationDbContext(optionsBuilder.Options))
                            {

                                //save or update() on *context* here
                            }

It turned out my test code had a small typo making it use the same DbContext across all threads. It is however required that I create a new DbContext instance but I cannot obtain one through the IServiceProvider as mentioned in my question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM