3

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();
}
4
  • And what exactly is your question? Commented Jan 18, 2019 at 9:43
  • My question is if it is possible to run the code snippet above in parallel? Because right now it runs synchronously. Commented Jan 18, 2019 at 9:44
  • 1
    Yes it is very possible, but you need to use Tasks and such, here is a tutorial on retrieving data asynchronously, should help Commented Jan 18, 2019 at 9:45
  • Possible duplicate of Is DbContext thread safe? Commented Jan 18, 2019 at 10:42

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.