I am calling a stored procedure via ASP.NET now I am trying to call it 200 times async, I am trying to do this by adding a transaction, however its not working out, here is my code:
try
{
using (connection = new SqlConnection(connectionString))
{
connection.Open();
transaction = connection.BeginTransaction();
for (int i = 0; i < 200; i++)
{
using (SqlCommand command = new SqlCommand("TimeSlotAppointments", connection))
{
command.Transaction = transaction;
command.CommandType = CommandType.StoredProcedure;
SqlParameter parameter1 = command.Parameters.Add("@StartTime", SqlDbType.DateTime);
parameter1.Direction = ParameterDirection.Input;
parameter1.Value = DateTime.Now;
command.ExecuteNonQuery();
}
}
transaction.Commit();
}
}
catch (SqlException e)
{
Console.Write(e);
transaction.Rollback();
}
finally
{
connection.Close();
connection.Dispose();
}
I am passing the current date and time as a parameter and when I check out the results in SQL Server I am expecting the @StartTime to be the same, but they are not, close, but the milliseconds increase for each record, am I going about this the wrong way? What I am trying to accomplish is executing the store procedure 200 times simultaneously.
DateTime.Nowin a variable once outside the loop and use it forparameter1.Value.@StartTimeto be the same, when you callDateTime.Now200 times? time passes ... However: what is this code actually trying to do? it seems unlikely that you'd want to run the exact same SQL with the same parameters - 200 times. Also, you're not actually calling it async ("now I am trying to call it 200 times async")for (i=0;i<200;i++){parameter1.Value=someNewValue;cmd.ExecuteNonQuery();}. A better solution is to avoid the loop entirely. What does the sproc do and why don't you pass all the values you need at once?