我正在尝试将一些代码移动到某些类文件中以清理我的代码。我遇到问题的一个方面是报告执行任务的对象和进度条之间的事件进度。
我想事件函数必须放在新类中,但是他们还需要更新调用表单上的进度条吗? class \ object可以代替事件处理程序返回更新吗?
目前,表单包含所有代码:
Function DoRestore(ByVal SQLServer As String, ByVal BackupFilePath As String, ByVal DatabaseName As String)
Dim Server As Server = New Server(SQLServer)
Server.ConnectionContext.ApplicationName = Application.ProductName
Dim res As Restore = New Restore()
Dim dt As DataTable
res.Devices.AddDevice(BackupFilePath, DeviceType.File)
dt = res.ReadFileList(Server)
res.Database = DatabaseName
res.PercentCompleteNotification = 1
AddHandler res.PercentComplete, AddressOf RestoreProgressEventHandler
AddHandler res.Complete, AddressOf RestoreCompleteEventHandler
res.SqlRestoreAsync(Server)
While res.AsyncStatus.ExecutionStatus = ExecutionStatus.InProgress
Application.DoEvents()
End While
End Function
Private Function RestoreProgressEventHandler(ByVal sender As Object, ByVal e As PercentCompleteEventArgs)
'Update progress bar (e.Percent)
End Function
Private Sub RestoreCompleteEventHandler(ByVal sender As Object, ByVal e As Microsoft.SqlServer.Management.Common.ServerMessageEventArgs)
'Signal completion
End Sub
通过:
使用DoRestore(SQLServer, "C:\SQLBACKUP.bak", DatabaseName)
答案 0 :(得分:10)
您应该在类中定义一个事件并在表单中处理进度条更新(假设WinForms?) - 这里的重点是该类关注备份某些东西 - 它不应该有任何进展的概念柱:
在班级中定义事件:
Public Event ReportProgress(byval progress as integer)
执行备份时根据需要提升此事件:
RaiseEvent ReportProgress(value)
在调用代码中,您需要
使用WithEvents
定义一个类:
Private WithEvents Backup As BackupClass
然后对事件采取行动:
Private Sub Backup _ReportProgress(progress As Integer) Handles Backup.ReportProgress
Debug.WriteLine("Progress:" + progress.ToString)
End Sub
或手动添加处理程序:
Private Sub Backup_ReportProgressHandler(progress As Integer)
Debug.WriteLine("Progress Handler:" + progress.ToString)
End Sub
AddHandler Backup.ReportProgress, AddressOf Backup_ReportProgressHandler
答案 1 :(得分:2)
嗯,你可以做到这一点,但说实话,如果更新表单进度条的事件处理程序之类的东西都是那种形式,我发现它不那么令人困惑。否则为了稍后维护它(例如修复进度条问题),我现在需要继续探险,找出你藏在哪里。
所以IMO,如果一个表单调用一个做某事的类,并且该类正在返回进度通知,那么在调用表单中处理这些通知是个好主意。