How to use sql transaction in multiple efcontexts and multi-thread in ef core

166 views Asked by At

Let's say I have 10 methods that will run in parallel. In each of them, I am creating a DbContext and making changes in the database. I CANNOT use one instance of DbContext, because every method will do a huge update and it will not be efficient. My code is like this:

var task1 = Task.Run(Method1);
var task2 = Task.Run(Method2);
var task3 = Task.Run(Method3);
var task10 = Task.Run(Method10);


Task.WaitAll(task1, task2, task3, task10);

void Method1()
{
    using (MyContext context = new MyContext())
    {
        //Huge update
    }
}

void Method2()
{
    using (MyContext context = new MyContext())
    {
        //Huge update
    }
}

void Method3()
{
    using (MyContext context = new MyContext())
    {
        //Huge update
    }
}

void Method10()
{
    using (MyContext context = new MyContext())
    {
        //huge update
    }
}


class MyContext : DbContext
{

}

The problem that I am trying to solve is:

When any of Method1, Method2 ... Method9 fails, changes of Method1, Method2 ... Method9 should not be saved, but it should save changes of Method10

I read something about TransactionScope, but it looks like when we don't commit it, changes of Method10 will not be saved. What is the proper way of implementing it?

1

There are 1 answers

1
Mahdi Anjam On
using  (var dbContext10= new DbContext())   
     { 
       using (var scope = new TransactionScope())
          {
                using (var dbContext1= new DbContext())
                {
                    using (var dbContext2= new DbContext())
                    {
                        //send context to your methods
                        //wait to all tasks after saveChanges
                    }
                }
          }
     }