Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DbContext in Parallel

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();
}
like image 984
Josh Monreal Avatar asked Mar 06 '26 18:03

Josh Monreal


1 Answers

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.

like image 51
gerwin Avatar answered Mar 08 '26 08:03

gerwin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!