Efcore: Cannot use dbcontext when it is in Task.Factory.StartNew();

Created on 12 Dec 2015  路  5Comments  路  Source: dotnet/efcore

I'm using rc1-final-update1. The db context cannot be called in a new thread. I am importing about 100,000 records, I don't want to wait it.

public IActionResult XXX([FromServices] SomeDbContext db)
{
    Task.Factory.StartNew(()=> {
        db.XXX.Add(new XX { xx = "123" });
        db.SaveChanges();
    });
    return Content("blablabla");
}

DbContext has been disposed in new thread.

It works with beta7, but it is no longer works after beta7.

/cc @rowanmiller @divega @natemcmaster

Most helpful comment

Thank you @davidfowl, It works with the following code.

using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>()
                        .CreateScope())
                    {
                        var context = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
                    }

All 5 comments

I suppose it is related to #3196

That's not a bug it's by design. You need to make a new scope in the background thread to use the db context there. You're introducing a race condition since the original db context might be disposed before your task runs.

Thank you @davidfowl, It works with the following code.

using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>()
                        .CreateScope())
                    {
                        var context = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
                    }

hey @Kagamine can you please share full codes? thanks

use serviceProvider diff serviceScopeFactory ?

Was this page helpful?
0 / 5 - 0 ratings