迟到的SqlCommand异步

    在开发过去的ERP版本,虽然有使用异步处理技术,图于便捷调用,直接使用了MS提供的BackgroundWorker控件,在DoWork事件中直接就执行ADO.NET的返回资料了。

目前正在筹备新版本的技术,重新温习了dotnetfx的异步技术,发现SqlCommand中自带的异步取数方式更为理想:现在做的一些练习代码记录如下:

 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button9.Click

        Dim sqlConn As New SqlConnection("Data Source=server;Initial Catalog=ERPData;Persist Security Info=True;User ID=sa;Asynchronous Processing=True;MultipleActiveResultSets=True;Password=XXX")

        Dim sqlcmd As New SqlClient.SqlCommand("Select * From WMoveList", sqlConn)

        Try

            sqlConn.Open()

 

            Dim sqldap As New SqlDataAdapter(sqlcmd)

            Dim ds As New DataSet

            '可以先获取返回的数据结构

            sqldap.FillSchema(ds, SchemaType.Mapped)

 

            Dim callBack As New AsyncCallback(AddressOf CallBackMethod)

            sqlcmd.BeginExecuteReader(callBack, sqlcmd, CommandBehavior.CloseConnection)

        Catch ex As Exception

 

            MessageBox.Show(ex.Message)

        Finally

 

        End Try

End Sub

 

Private Sub CallBackMethod(ByVal IResult As IAsyncResult)

        Dim cmd As SqlCommand = CType(IResult.AsyncState, SqlCommand)

        Dim dr As SqlDataReader = cmd.EndExecuteReader(IResult)

 

        '因线程不一样,要操作界面元素,必须通过代理的方式

        Dim d As New SetGridData(AddressOf SetGridData2)

        Me.Invoke(d, New Object() {dr})

End Sub

 

Private Delegate Sub SetGridData(ByVal dr As SqlDataReader)

 

Private Sub SetGridData2(ByVal dr As SqlDataReader)

 

        '這樣子可以獲得輸出表的結構

        Dim dtField As DataTable = dr.GetSchemaTable()

        MessageBox.Show(dtField.Rows.Count)

 

        MessageBox.Show(dr.FieldCount)

 

        Dim c As Integer = 0

        While dr.Read()

            c += 1

        End While

 

        MessageBox.Show(c)

 

        dr.Close()

End Sub

 

以此方式再结合WCF的大数据量的流传输方式,实现续传。大有所为!

你可能感兴趣的:(exception,Integer,processing,callback,button,dataset)