Parallel foreach error

Posts   
 
    
Jed
User
Posts: 38
Joined: 08-Oct-2010
# Posted on: 03-Mar-2011 09:29:40   
using (var ts = new TransactionScope())
                                         using (var adapter = Data.Rad.DatabaseSpecific.DataAccessAdapter.GetAdapter())
                                         {
                                             Parallel.ForEach(
                                                 invoiceCol
                                                 , invoice =>
                                                       {

Within this foreach i add a entity to the database.

When i run this i get the error

An exception was caught during the execution of an action query: The ConnectionString property has not been initialized.. Check InnerException, QueryExecuted and Parameters of this exception to examine the cause of this exception.

Any suggestions

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39908
Joined: 17-Aug-2003
# Posted on: 03-Mar-2011 11:16:09   

This is logical, Parallel.ForEach starts multiple threads, and all of them will use the same or different data-access adapter instances. Only use Parallel.ForEach over elements in memory, not on elements pulled live from a db.

Frans Bouma | Lead developer LLBLGen Pro
Jed
User
Posts: 38
Joined: 08-Oct-2010
# Posted on: 03-Mar-2011 11:26:24   

I am processing close to 500 000 entities in a collection. Is there any way i can use multiple threads to improve speed. When saving to the the database.

If i use this there are no errors however i do not want to open a connection for every thread.

using (var ts = new TransactionScope()) { Parallel.ForEach( invoiceCol , invoice => { using (var adapter = Data.Rad.DatabaseSpecific.DataAccessAdapter.GetAdapter()) { save entity here

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 03-Mar-2011 11:44:43   

I don't think a db connection is safe for multithreading. (SQLConnection is not thread safe).