c# - DbContextTransaction and Multi-thread: The connection is already in a transaction and cannot participate in another transaction -


i got error when trying call same method multiple threads: the connection in transaction , cannot participate in transaction. entityclient not support parallel transactions.

and found issue somehow similar this: sqlexception entity framework - new transaction not allowed because there other threads running in session

my scenario: have class instantiated multiple theads, each thread - new instance:

public marketlogic() {        var dbcontext = new financialcontext();       accountbalancerepository = new accountbalancerepository(dbcontext);       compositetraderepository = new compositetraderepository(          new orderrepository(dbcontext)          , new positionrepository(dbcontext)          , new traderepository(dbcontext));        compositerepository = new compositerepository(          new lookupvaluerepository(dbcontext)          , new securityrepository(dbcontext)          , new transactionrepository(dbcontext)          , new financialmarketrepository(dbcontext)          , new financialmarketsessionrepository(dbcontext)          ); } 

in marketlogic class, saveposition() used save information database using entity framework dbcontext. (savechanges()) method.

private void saveposition() {    using (dbcontexttransaction transaction = compositetraderepository.orderrepository.dbcontext.database.begintransaction())    {             try             {                    // business logic code, **this take times complete**.                    position = entityexistsspecification.not().issatisfiedby(position)                               ? compositetraderepository.positionrepository.add(position)                               : compositetraderepository.positionrepository.update(position);                    transaction.commit();             }             catch (exception exception)             {                 // code                 transaction.rollback();             }     } }  public position add(position position) {    // code    // context instance of financialcontext, class generated entity framework 6    context.savechanges(); } 

in scenario, issue happened when there 2 threads , more try call new marketlogic().saveposition().

i can see while first transaction not completed yet, second thread come in , start new transaction.

but dont understand why 2 threads in different dbcontext object error still happens

so wrong? or did miss something?

my fault, left repositories static, thread shared same repositories, means shared same dbcontext, caused issue when ef didn't finished permitting changes yet , other call savechanges() made. ef throwed exception.


Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -