在异步进程中提交/回滚SQ​​L事务

时间:2017-08-31 10:20:24

标签: sql-server vb.net asynchronous commit rollback

是否可以在异步进程中提交和回滚事务?

我正在使用Vb.Net和SQL Server。我的代码是:

 If connString.ToString.ToUpper.Contains("ASYNCHRONOUS PROCESSING=TRUE") = False Then
        connString = connString & ";Asynchronous Processing=True;"
    End If
    Using cn As New SqlConnection(connString)
        cn.Open()
        Dim tr As SqlTransaction = cn.BeginTransaction()
        Using tr
            Using cmd As New SqlCommand(sql, cn)
                cmd.Transaction = tr
                Try
                    Dim count As Integer = 0
                    Dim result As IAsyncResult = cmd.BeginExecuteNonQuery()
                    While Not result.IsCompleted

                        Threading.Thread.Sleep(100)
                        count += 1
                    End While


                Catch ex As Exception

                    tr.Rollback()
                    lSuccess = False
                    ErrMsg = ex.ToString


                    GoTo skip
                End Try
            End Using

            tr.Commit()

        End Using
skip:       If Not cn.State = ConnectionState.Closed Then cn.Close()

    End Using
End If

如果事务成功完成,它会在tr.Rollback行中生成错误,指出SQLTransaction已完成且不再可用。

请帮助。谢谢!

0 个答案:

没有答案