异步运行存储过程

时间:2015-11-02 22:15:41

标签: c# stored-procedures

我一直在玩下面的代码。单击该按钮时,想法是存储过程运行并使用随机数量的虚拟记录更新表(现在,无论如何我都在玩)。

protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection("Data Source=MATT\\RICHARDSON2008R2;Initial Catalog=Minerva;User ID=User;Password=password; Asynchronous Processing=True");
            SqlCommand cmd = new SqlCommand("exec UpdateRandomData '" + UpdateID.Text + "'",conn);

            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }

我编写的存储过程使用循环添加100000行(模拟可能需要一段时间才能运行的过程): -

ALTER procedure [dbo].[UpdateRandomData]
    @updateID varchar(50)
as
declare @count int = 1;
declare @theDate datetime = getdate();
declare @total int  =FLOOR(rand() * 100000);

while @count < 100001
begin
    insert into RandomData (randnumber, updateID, updatedDate)
    values 
    (FLOOR(rand() * 1001), @updateID, @theDate)
    set @count += 1;
end
GO

当我运行上面的C#代码时,我会在存储过程完成运行之前得到超时,所以我尝试了cmd.ExecuteNonQueryAsync();: -

conn.Open();
cmd.ExecuteNonQueryAsync();
conn.Close();

问题在于它似乎没有按照我期望的方式工作,我只从存储过程中向表中添加一行。

有人能指出我正确的方向,为什么这不能按我的意愿工作?

3 个答案:

答案 0 :(得分:6)

异步运行不是解决方案。你必须改变超时。您可以调整SqlCommand's timeout。它是一个整数,表示等待响应的秒数。我通常这样设置它以避免混淆:

cmd.CommandTimeout = TimeSpan.FromMinutes(30).TotalSeconds;

要无限期等待,请将“命令超时”设置为零。我想你还需要设置SqlConnection的ConnectionTimeout属性。

此外,您应该对SqlConnection和SqlCommand对象使用using模式。

答案 1 :(得分:4)

你是说这个?:

using System.Threading.Tasks;

protected void Button1_Click(object sender, EventArgs e)
    {
        Task.Run(() => {
                   SqlConnection conn = new SqlConnection("Data Source=MATT\\RICHARDSON2008R2;Initial Catalog=Minerva;User ID=User;Password=password; Asynchronous Processing=True");
                   SqlCommand cmd = new SqlCommand("exec UpdateRandomData '" + UpdateID.Text + "'",conn);

                   conn.Open();
                   cmd.ExecuteNonQuery();
                   conn.Close();
              })
    }

答案 2 :(得分:0)

实现这一目标的一种方法是使用sp_start_job

这允许你执行sp而不是等待它完成。

相关问题