Insert using parallel for loop error : The connection was not closed. The connections current state
Please check code revert ASAP.
protected void Insert(object sender, EventArgs e)
{
string constr = "Data Source=;Initial Catalog=Test;User ID=uid;Password=psw;";
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = null;
try
{
Parallel.For(0, 100, j =>
{
cmd = new SqlCommand("INSERT INTO tbl_CustomerData VALUES(@Name,@Country)", con);
cmd.Parameters.AddWithValue("@Name", "Ajeet");
cmd.Parameters.AddWithValue("@Country", "India");
if (cmd.Connection.State != ConnectionState.Open)
{
cmd.Connection.Close();
cmd.Connection.Open();
}
cmd.ExecuteNonQuery();
});
}
catch (SqlException exce)
{
throw;
}
finally
{
con.Close();
}
}