-1

I'm using the below to restore a database in VB.NET. This works but causes the interface to lockup if the user clicks anything. Also, I cannot get the progress label to update incrementally, it's blank until the backup is complete then displays 100%

Sub DoRestore()
    Dim svr As Server = New Server("Server\SQL2008")
    Dim res As Restore = New Restore()
    res.Devices.AddDevice("C:\MyDB.bak", DeviceType.File)
    res.Database = "MyDB"
    res.RelocateFiles.Add(New RelocateFile("MyDB_Data", "C:\MyDB.mdf"))
    res.RelocateFiles.Add(New RelocateFile("MyDB_Log", "C:\MyDB.ldf"))
    res.PercentCompleteNotification = 1
    AddHandler res.PercentComplete, AddressOf ProgressEventHandler
    res.SqlRestore(svr)
End Sub

Is this change correct?:

Private Sub ProgressEventHandler(ByVal sender As Object, ByVal e As PercentCompleteEventArgs)
    UpdateProgressBar(e.Percent)
End Sub

Private Sub UpdateProgressBar(ByVal e As String)
    ProgressBar.Value = e
    Status.Text = e.ToString
End Sub
madlan
  • 11
  • 4
  • By the way just a suggestion you might want to edit the title of this because what you are really asking is "How can I avoid the 'Cross-thread operation not valid' error when updating UI elements". This is more likely to attract the attention of someone that knows the answer off the top of their head. – Martin Smith Jun 08 '10 at 14:15

1 Answers1

0

You need to use SqlRestoreAsync not SqlRestore to prevent it tying up your main thread.

Then to avoid the Cross Thread Operation error when updating the UI you can use the approach here. Where you create a method on the form that will update the UI elements and call that from your asynch handler using Invoke.

Community
  • 1
  • 1
Martin Smith
  • 438,706
  • 87
  • 741
  • 845
  • Hi Martin, the SqlRestoreAsync prevents the progress handler from updating the label and progress bar: Cross-thread operation not valid: Control 'Label3' accessed from a thread other than the thread it was created on. – madlan Jun 06 '10 at 14:54
  • Is the above change correct? I've added an update sub on the main UI thread which is being passed the percent complete from the progress event handler sub. The progress bar seems to finish way before the restore process is complete and the label is not updated at all. – madlan Jun 06 '10 at 16:24
  • No I don't think that's right but I'm surprised it didn't give you any errors. I thought you had to use `Invoke` or a `backgroundworker`. It's not something I know about off the top of my head. Maybe have a look at this project which seems very similar to yours http://www.shabdar.org/sql-server-backup-utility.html – Martin Smith Jun 06 '10 at 17:09