如何通过 VB.Net 在 Azure SQL 数据库上执行完全异步查询?

问题描述 投票:0回答:1

我有一个连接到 Azure SQL Server 的 ASP.Net 网站。

我需要执行一个存储过程,主要由一条插入语句组成,运行大约需要 8 分钟。

我通常会通过网站的 VB.Net 代码中的 SqlCommand.ExecuteNonQuery 执行此操作。

但是,在这种情况下,由于运行时间为 8 分钟,这样做会导致网站超时。

我需要一种异步执行此查询的方法,以便网站将命令发送到服务器并立即恢复操作而不等待结果。当我稍后检查相关表格时,是否有问题就会很明显。

我无法使用服务代理,因为 Azure 不允许使用它,并且如果没有 Azure 托管实例,我无法设置作业。

我尝试过 SqlCommand.BeginExecuteNonQuery,它确实允许我单击代码后面的按钮,然后立即返回在网站中执行其他操作,但似乎并未实际运行查询,我猜这是因为我的代码到达事件结束并在实际完成之前取消查询。

有办法做到这一点吗?

当前代码...

Protected Sub Button_Click(sender As Object, e As System.EventArgs) Handles Button.Click

txtUsrID.Value = Session.Item("s_lngUsrID")
txtUsrTypIDfk.Value = Session.Item("s_lngUsrTypIDfk")


'Set up the command variables
Dim Cnn As SqlConnection
Dim Cmd As SqlCommand

Cnn = New SqlConnection
Cnn.ConnectionString = "TheString"
Cmd = New SqlCommand
Cmd.CommandType = Data.CommandType.StoredProcedure

'Retrieve the record count
Cmd.CommandText = "sptblTemp_GndrRprtPrGrp_Insrt"
Cmd.Parameters.Add("@UsrIDfk", Data.SqlDbType.Int).Direction = Data.ParameterDirection.Input
Cmd.Parameters("@UsrIDfk").Value = txtUsrID.Value

Try
    Cnn.Open()
    Cmd.Connection = Cnn
    Cmd.CommandTimeout = 0
    Cmd.BeginExecuteNonQuery()


Catch Excptn As Exception

    txtMssgs.Value = Excptn.Message

End Try

'clean up
Cmd.Parameters.RemoveAt("@UsrIDfk")


'close the connection if it's open
If Cnn.State = Data.ConnectionState.Open Then
    Cnn.Close()
End If
Cmd.Dispose()
Cnn.Dispose()

结束子

asp.net vb.net azure-sql-database
1个回答
0
投票
  1. 向您的 ASP 项目添加一个模块,命名为类似 “公共模块”。
  2. 在该模块中,您将把代码和结果作为 Public、子例程和 Public 结果对象。
  3. 在单击按钮时,您检查 Result 对象是否为 什么都没有或者是空的。如果是,则创建一个线程来调用该子例程 查询并填充公共结果。第一次单击将创建线程/查询/结果。线程将继续 8 分钟就可以了。

公共结果对象将永远保留在该 IIS 进程中 - 直到进程回收。

由于这需要 8 分钟,您可能需要设置一个变量来告诉下一个用户/下一次单击查询正在进行中。

© www.soinside.com 2019 - 2024. All rights reserved.