具有异步功能的OracleCommand ExecuteNonQuery

时间:2020-02-12 16:46:49

标签: vb.net asynchronous odp.net

Public Function ExecuteNonQuery(ByVal cmd As OracleCommand) As Integer
    ' no of affected rows ...
    Dim affectedRows As Integer = -1
    ' execute the command ...
    Try
        ' open connection ...
        cmd.Connection.Open()
    Catch ex As Exception
        MsgBox("Unable to establish a connection to database." & ex.ToString, MsgBoxStyle.Critical)
        Exit Function
    End Try
    Try
        ' execute command ...
        'affectedRows = cmd.ExecuteNonQuery()
        affectedRows = cmd.ExecuteNonQuery()

    Catch ex As OracleClient.OracleException
        If CInt(ex.Code) = CInt(1) Then
            Return -2
        End If

    Catch ex As Exception
        ' rethrow error ...
        'Dim cfrErr As New CFR_Errors("Data_Access_Class","ExecuteNonQuery", ex)
        Throw New Exception(ex.InnerException.ToString, ex)
    Finally
        cmd.Connection.Close()
    End Try
    Return affectedRows
End Function

如何使用Oracle.ManagedDataAccess执行异步查询?我们正在将数据库更改为AWS,这可能会导致延迟,

1 个答案:

答案 0 :(得分:1)

由于Async足够简单,可以重构为使用AwaitDbConnectionDbCommand应该具有异步API。

Public Async Function ExecuteNonQueryAsync(ByVal cmd As DbCommand) As Task(Of Integer)
    ' no of affected rows ...
    Dim affectedRows As Integer = -1
    ' execute the command ...
    Try
        ' open connection ...
        Await cmd.Connection.OpenAsync()
    Catch ex As Exception
        MsgBox("Unable to establish a connection to CFR database." & ex.ToString, MsgBoxStyle.Critical)
        Exit Function
    End Try
    Try
        ' execute command ...
        affectedRows = Await cmd.ExecuteNonQueryAsync()

    Catch ex As OracleClient.OracleException
        If CInt(ex.Code) = CInt(1) Then
            Return -2
        End If

    Catch ex As Exception
        ' rethrow error ...
        Throw New Exception(ex.InnerException.ToString, ex)
    Finally
        cmd.Connection.Close()
    End Try
    Return affectedRows
End Function

参考Asynchronous programming with Async and Await (Visual Basic)