VB.NET 2.0:
我正在从 VB.NET 应用程序向 SQL 服务器发出备份命令。我正在捕获它发出的消息并将它们附加到多行文本框中。
不过,我想做的是让应用程序继续响应 GUI 控制事件(主要是为了让用户可以调整输出窗口的大小或取消备份)。所以我BeginExecuteReader
在一个循环中使用和旋转Application.DoEvents()
. 但似乎一旦备份开始发出它的打印语句,我得到IAsyncResult.IsCompleted = True
它并下降到EndExecuteReader
,并且 GUI 现在再次被锁定。我怎样才能让它留在循环中,直到备份命令完成,但仍然得到那些输出语句并保持 GUI 响应?谢谢。
这是我的代码:
' 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