user1595214
user1595214

Reputation: 551

parallel.for loop giving timeout exception

I am using Parallel.For to make concurrent calls as following.

 SqlConnection connection = new SqlConnection(connectionString);                          
 connection.Open();
 SqlCommand cmd = new SqlCommand();
 //SqlDataReader reader;                            
 cmd.CommandType = CommandType.Text;
 cmd.Connection = connection;
 Parallel.For(0, 100, delegate(int i)
 {
  //insert into database;
  cmd.CommandText = string.Format("insert into Service_LoadTest(id,ServiceCallcount) values ({0},'Call_{1}')", i, i);                               
  cmd.ExecuteNonQuery();
  });

After inserting some counts upto 70 ,i am getting timeout exception as "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.".I have set the connetion string timeout property,but of no luck. Please help.

Upvotes: 0

Views: 1379

Answers (2)

RagtimeWilly
RagtimeWilly

Reputation: 5445

Your code isn't thread-safe. Try moving all code into the loop:

Parallel.For(0, 100, delegate(int i)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {                          
        connection.Open();

        SqlCommand cmd = new SqlCommand();

        cmd.CommandType = CommandType.Text;
        cmd.Connection = connection;

        cmd.CommandText = string.Format("insert into Service_LoadTest(id,ServiceCallcount) values ({0},'Call_{1}')", i, i);                               
        cmd.ExecuteNonQuery();
    }
});

Upvotes: 3

ATP
ATP

Reputation: 561

Instead of creating SqlConnection and SqlCommand objects each time and and intialising those to call ExecuteNonQuery separately for each query you should concatenate all queries and call ExecuteNonQuery only once for that concatenated query.

For implementing above just append all queries in CommandText seperated by ';' and then call ExecuteNonQuery.

Upvotes: 2

Related Questions