Click here to Skip to main content
15,886,795 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
I have a situation here, I need to insert a record in 10 tables and that's need to b atomic in nature hence I am using transaction, this need to be done for a collection of records and need to have better performance hence can't use sequential approach. However the SQL Transactions are causing deadlock in Parallel.ForEach and thus I need a different solution. Could anyone please advise how I can achieve this parallel processing with encountering any deadlocks??


What I have tried:

C#
int[] itemListArr = GetAllItems();
        Parallel.ForEach(Partitioner.Create(0, itemListArr.Count(), 5),
            new ParallelOptions { MaxDegreeOfParallelism = 8 },
            (range) =>
            {
                for (int i = rangeFrom; i < rangeTo; i++)
                {
                    _database.BeginTransaction(connectionString);
                    try
                    {
                        foreach (var table in _template.Tables)
                        {

                            sqlCmd = string.Format(insertQuery, table.DestinationTable, strColumns, strColumnsValue);
                            _database.InsertWithMultiTransaction(sqlCmd);
                        }

                        _database.CommitTransaction();
                    }
                    catch (Exception ex)
                    {
                        _database.RollbackTransaction();
                    }

                }
            });
Posted
Updated 25-Jul-19 21:17pm
Comments
Richard Deeming 26-Jul-19 9:38am    
sqlCmd = string.Format(insertQuery, table.DestinationTable, strColumns, strColumnsValue);

Don't do it like that!

Your code is almost certainly vulnerable to SQL Injection[^]. NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]

1 solution

Your variable _database seems to be defined outside the parallel.foreach. Then each thread is using the same object. You should instantiate _database IN the parallel.foreach. Then each thread has it's own call to the database.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900