ASP.NET多次执行SQL Server存储过程异步

时间:2017-04-04 15:28:44

标签: c# asp.net sql-server stored-procedures

我现在通过ASP.NET调用存储过程我试图将其称为200次异步,我试图通过添加一个事务来做到这一点,但是它没有用,这是我的代码:

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次存储过程。

1 个答案:

答案 0 :(得分: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();
}