2017-04-04 81 views
0

我通过ASP.NET调用存储过程现在我试图调用它200次异步,我试图通过添加一个事务来做到这一点,但它不工作出去,这里是我的代码:ASP.NET多次执行SQL Server存储过程异步

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(); 
} 

我传递当前日期和时间为参数,当我检查了在SQL Server中的结果,我期待@StartTime是相同的,但他们都没有,关闭,但每条记录的毫秒数增加,我是否会以错误的方式回答这个问题?我试图完成的是同时执行存储过程200次。

+2

如果你想在日期时间是相同的所有记录,然后一旦存储'DateTime.Now'在一个变量外循环,并用它来'参数1。 Value'。 –

+1

当你调用'DateTime.Now' 200次时,为什么你会期望'@ StartTime'是相同的?时间流逝......但是:这段代码实际上试图做什么?您似乎不太可能希望使用相同的参数运行完全相同的SQL - 200次。此外,你实际上并没有把它叫做异步(“现在我试图称它为200次异步”) –

+5

我有一种感觉,这是一个XY问题。 https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem –

回答

1

开始时间值是不同的,因为您正在分配循环内的值,并且在每次迭代中,时间已经改变(如您所提及的几毫秒)。如果要为所有呼叫使用相同的值,则需要将循环外的时间戳存储在变量中,并在循环中使用该值。 这是你的代码应该如何看起来像:

try 
{ 
    using (connection = new SqlConnection(connectionString)) 
    { 
     connection.Open(); 
     transaction = connection.BeginTransaction(); 
     var startTime = DateTime.Now; // I added this line 

     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 = startTime; // I changed this line 

       command.ExecuteNonQuery(); 
      } 
     } 

     transaction.Commit(); 
    } 
} 
catch (SqlException e) 
{ 
    Console.Write(e); 
    transaction.Rollback(); 
} 
finally 
{ 
    connection.Close(); 
    connection.Dispose(); 
}