ADO.NETの基本的なコード:「SQLの非同期実行」(その2)

実際にコードを書いてみるとこんな感じ

 Dim SqlCommand As New Data.SqlClient.SqlCommand("処理の重いSQL文")
 Using asyncDBConnection As New System.Data.SqlClient.SqlConnection(DBConnectionString)
 ※DBConnectionStringには「async=true」を加えておく
  Try
   asyncDBConnection.Open()
   SqlCommand.Connection = asyncDBConnection

   Dim result As IAsyncResult = SqlCommand.BeginExecuteNonQuery()
   While Not result.IsCompleted
    ※SQL文が完了するまで待つループ
    Threading.Thread.Sleep(100)
    System.Windows.Forms.Application.DoEvents()
    ※とりあえずDoEventsでUIが固まらないようにするよ
   End While

   SqlCommand.EndExecuteNonQuery(result)
  Catch ex As Exception
   MsgBox(ex.Message)
   ※発生した例外のメッセージを表示してみる
  End Try
 End Using
書いてみると結構簡単
これで処理が重いSQL文を発行してもUIが固まらなくなった。