Is it possible to use parallelism in Entity Framework's DbContext? Basically I have an application that adds thousands of records for each of the 4 tables that I have. And I am thinking that the best way to optimize it is to have the adding of records done in parallel.
public void Transact()
{
var context = new DbContext();
_fooList = new List<Foo>
{
//… Assume that this list contains thousands of objects
}
context.Set<Foo>().AddRange(_fooList);
var context1 = new DbContext();
_barList = new List<Bar>
{
//… Assume that this list contains thousands of objects
}
context1.Set<Bar>().AddRange(_barList);
context.SaveChanges();
context1.SaveChanges();
}
Please see this StackOverflow thread: Is DbContext thread safe?
The DbContext is not thread-safe, but you can instantiate a new one for each thread. If you use Tasks and such, make sure to instantiate a new DbContext for each one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With