VB.NET 2.0:
I’m issuing a backup command to a SQL server from a VB.NET application. I’m capturing the messages it sends out and appending them to a multiline textbox.
What I’m trying to do, though, is to allow the application to keep responding to GUI control events (mainly so that the user can resize the output window or cancel the backup). So I use BeginExecuteReader and spin in a loop with Application.DoEvents(). But it seems that as soon as the backup starts issuing its print statements, I get IAsyncResult.IsCompleted = True and it drops down to EndExecuteReader, and the GUI is now locked up again. How can I get it to stay in the loop until the backup command completes and yet still get those output statements and keep the GUI responsive? Thanks.
Here’s my code:
' Enable retrieve print statements from the server'
AddHandler oConn.InfoMessage, AddressOf LogToBufferHandler
strSQL &= vbNewLine & "begin try"
strSQL &= vbNewLine & " declare @BackupName as varchar(255)"
strSQL &= vbNewLine & " declare @BackupDesc as varchar(255)"
strSQL &= vbNewLine & " declare @backupTime as varchar(50)"
strSQL &= vbNewLine & " set @backupTime = (select convert(datetime, getdate(), 100))"
strSQL &= vbNewLine & " set @BackupName = (SELECT '[' + db_name() + '] Full Backup')"
strSQL &= vbNewLine & " set @BackupDesc = (SELECT 'Automated full backup of [' + db_name() + '] on ' + @backupTime + '.')"
strSQL &= vbNewLine & " "
strSQL &= vbNewLine & " BACKUP DATABASE [#Database#]"
strSQL &= vbNewLine & " TO DISK = @BackupFullPath"
strSQL &= vbNewLine & " WITH stats,"
strSQL &= vbNewLine & " NAME = @BackupName,"
strSQL &= vbNewLine & " DESCRIPTION = @BackupDesc;"
strSQL &= vbNewLine & " select [IsSuccessful] = 1"
strSQL &= vbNewLine & " end try"
strSQL &= vbNewLine & " begin catch"
strSQL &= vbNewLine & " SELECT [IsSuccessful] = 0"
strSQL &= vbNewLine & " end catch"
'Workaround: Backup Database requires the name of the object, not a string'
' and I dont want to use dynamic SQL.'
strSQL = strSQL.Replace("#Database#", sb.InitialCatalog)
oConn.Open()
oCmd = New SqlCommand()
oCmd.Connection = oConn
oCmd.CommandText = strSQL
oCmd.CommandType = CommandType.Text
oCmd.Parameters.AddWithValue("@BackupFullPath", backupFullPath)
oCmd.CommandTimeout = 60 * 5
'Spin until complete, cancel, or timeout'
Dim result As IAsyncResult = oCmd.BeginExecuteReader(CommandBehavior.CloseConnection)
While Not result.IsCompleted
Application.DoEvents()
If blnCancel Then
oCmd.Cancel()
End If
System.Threading.Thread.Sleep(50)
End While
Try
oDataReader = oCmd.EndExecuteReader(result)
oDataTable.Load(oDataReader)
'Get results'
' (unfourtunately, you cannot do BeginExecuteScalar ASync in .Net 2.0,'
' so we are using a DataTable first column, row)'
If oDataTable IsNot Nothing _
AndAlso oDataTable.Rows.Count > 0 _
AndAlso oDataTable.Columns.Contains("IsSuccessful") _
AndAlso oDataTable.Rows(0).Item("IsSuccessful") = 1 Then
eBackupResult = BackupStatus.Succeeded
returnPath = backupFullPath 'Only set return path if the backup succeeded'
Else
eBackupResult = BackupStatus.Failed
End If
Catch ex As Exception
If Not ex.Message.Contains("cancelled by user") Then Throw ex
eBackupResult = BackupStatus.Canceled
End Try
Polling loops (
DoEvents) are considered evil for many reasons. It is probably the easiest way for you to switch toBackgroundWorkerand abandon the nasty Begin-poll-End scheme.If you want to keep it, here is the bug: Accepting the reader can be quick but that doesn’t mean that all results have arrived (let me illustrate: what if you had queried 1TB of data? – reading that is a long process). You need to
Readin an async (polling) way too. Now the thing gets out of hand. Just abandon it.In other words,
oDataTable.Loadis blocking which is hard to fix.