在另一个类中处理事件
问题描述:
我试图将一些代码移入某些类文件以清理我的代码。我遇到的一个问题是报告执行任务的对象与进度条之间的事件进度。在另一个类中处理事件
我想事件函数必须放在新类中,但他们也需要更新调用窗体上的进度条? 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)
答
你应该在你的类中定义一个事件并处理表单中的进度条更新(假设为WinForms?) - 这里的重点是该类是关于备份的东西 - 它不应该有任何概念进度条:做备份时
Public Event ReportProgress(byval progress as integer)
引发此事件的要求:
RaiseEvent ReportProgress(value)
在T
定义在类的事件他调用代码,你要么需要
-
使用
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
+0
你可以通过让另一个子类将自定义事件提升到你的控制器类来级联。控制器中的事件处理程序然后调用backgroundworker上的ReportProgress来更新前端线程中的GUI。 – Andreas
答
那么你可以这样做,但说实话我觉得少混乱,如果事情像事件处理程序更新窗体的进度条就是这种形式。否则,为了在稍后维护它(例如修复进度条问题),我现在需要进行远征计算以确定您将其隐藏的位置。
所以IMO,如果窗体调用的类,它的东西,那类返回进度的通知,这是处理在调用形式这些通知是一个好主意。
你会用这段代码让自己陷入相当深的麻烦。检查这个答案:http://stackoverflow.com/questions/5181777/c-application-doevents/5183623#5183623 –