Cannot use dbcontext when it is in Task.Factory.StartNew();
See original GitHub issueI’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.
Issue Analytics
- State:
- Created 8 years ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
Task.Factory how to create new DbContext?
Just create a new context and use await with async versions of EF rather than calling Task.Factory.StartNew() . The latter is a poor...
Read more >Advanced Tips for Using Task.Run with Async/Await
Run with Async/Await and determine whether or not we should use Task. ... Factory.StartNew was introduced before Task.Run and is more configurable.
Read more >Task-based asynchronous programming - .NET
In this article, learn about task-based asynchronous programming through the Task Parallel Library ... You can also use the TaskFactory.
Read more >Cannot access a disposed object in ASP.NET Core when ...
Working with ASP.NET core I have seen this error multiple times and can be hard to debug. The error can have multiple root...
Read more >Running Async Calls with DbContext in Entity Framework
I want to be able to run an asynchronous call as follows: [Route("doit"),ResponseType(typeof(MyModel))] public IHttpResponse PostAsyncCall(MyModel model){ ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
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.