1

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();
}
Josh Monreal
  • 754
  • 1
  • 9
  • 29
  • And what exactly is your question? – MindSwipe Jan 18 '19 at 09:43
  • My question is if it is possible to run the code snippet above in parallel? Because right now it runs synchronously. – Josh Monreal Jan 18 '19 at 09:44
  • 1
    Yes it is very possible, but you need to use Tasks and such, [here](https://riptutorial.com/entity-framework/example/13437/execute-multiple-queries-async-and-in-parallel) is a tutorial on retrieving data asynchronously, should help – MindSwipe Jan 18 '19 at 09:45
  • Possible duplicate of [Is DbContext thread safe?](https://stackoverflow.com/questions/6126616/is-dbcontext-thread-safe) – mjwills Jan 18 '19 at 10:42

2 Answers2

1

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.

gerwin
  • 834
  • 5
  • 12
1

It is very possible, and faster (if used correctly, more on this later)
And here is how you could do it:

var context1 = new DbContext();
_fooList = new List<Foo>
{
    // Thousands of datasets
}

context1.Set<Foo>().AddRange(_fooList);

var context2 = new DbContext();
_barList = new List<Bar>
{
    // Thousands of datasets
}

context2.Set<Bar>().AddRange(_barList);

var fooTask = context1.SaveChangesAsync();
var barTask = context2.SaveChangesAsync();

await Task.WhenAll(new Task[] {fooTask, barTask});

This is faster than having one Context write to one table and then the next, but if you're doing this on the same table it might actually be slower than doing it with 1 Context

MindSwipe
  • 7,193
  • 24
  • 47