Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles Button1.Click
Dim builder As New SqlConnectionStringBuilder
''SQL接続文字(Settingなどを利用しましょう)
With builder
.UserID = "userid"
.Password = "password"
.DataSource = "server"
.InitialCatalog = "database"
.AsynchronousProcessing = True '非同期を有効
End With
''SQL接続
Using conn As SqlConnection = New SqlConnection(builder.ConnectionString)
''SQLコマンド
''非同期を実感するためにWAITFOR DELAYで一時待機させます
Using cmd As New SqlCommand("WAITFOR DELAY '00:00:03';" & _
"SELECT COUNT(*) AS ALL_COUNT FROM TABLE", conn)
''コネクションオープン
conn.Open()
''非同期で実行
Dim iar As IAsyncResult = cmd.BeginExecuteReader()
Console.WriteLine("処理開始")
''処理が完了するまで待機
Console.Write("処理中")
While Not iar.IsCompleted
Console.Write(".")
System.Threading.Thread.Sleep(500)
End While
Console.WriteLine()
Console.WriteLine("処理終了")
''データ取得
Using dr As SqlDataReader = cmd.EndExecuteReader(iar)
If (dr.HasRows = True) Then
If (dr.Read = True) Then
Console.WriteLine("{0}件取得しました", dr("ALL_COUNT"))
End If
End If
End Using
End Using
End Using
End Sub
End Class
|