2011-09-02 10 views
4

코드를 정리하기 위해 일부 코드를 일부 클래스 파일로 옮기려고합니다. 문제가있는 한 가지 영역은 작업을 수행하는 개체와 진행률 표시 줄 사이의 이벤트 진행 상태를보고하는 것입니다.다른 클래스의 이벤트 처리

이벤트 함수를 새 클래스에 배치해야하지만 호출 폼의 진행률 막대를 업데이트해야한다고 생각하십니까? 클래스 \ 객체가 이벤트 처리기 대신에 업데이트를 반환 할 수 있습니까?

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

이 코드를 사용하면 매우 심각한 문제가 발생할 것입니다. 이 답변을 확인하십시오 : http://stackoverflow.com/questions/5181777/c-application-doevents/5183623#5183623 –

답변

10

클래스에서 이벤트를 정의하고 진행률 막대 업데이트를 양식에서 처리해야합니다 (WinForms라고 가정). 여기서 핵심은 클래스가 어떤 것을 백업하는 것과 관련되어 있다는 점입니다. 진행률 표시 줄 : 필요에 따라 백업을 수행 할 때

Public Event ReportProgress(byval progress as integer) 

올립니다 이벤트 :

RaiseEvent ReportProgress(value) 

t에서를

클래스에서 이벤트를 정의

Private WithEvents Backup As BackupClass 

을 다음 이벤트에 따라 행동 :

Private Sub Backup _ReportProgress(progress As Integer) Handles Backup.ReportProgress 
    Debug.WriteLine("Progress:" + progress.ToString) 
End Sub 
  • 또는 수동으로 처리기를 추가 :

    을 그는 WithEvents를 사용하여 클래스를 정의 코드 당신에게

    • 에 하나의 필요성을 호출

      Private Sub Backup_ReportProgressHandler(progress As Integer) 
          Debug.WriteLine("Progress Handler:" + progress.ToString) 
      End Sub 
      
      AddHandler Backup.ReportProgress, AddressOf Backup_ReportProgressHandler 
      
  • +0

    컨트롤러 클래스에 사용자 지정 이벤트를 발생시키는 다른 자식 클래스를 추가하여이 작업을 계단식으로 수행 할 수 있습니다. 그런 다음 컨트롤러의 이벤트 핸들러가 백그라운드 작업자의 ReportProgress를 호출하여 프런트 엔드 스레드의 GUI를 업데이트합니다. – Andreas

    2

    그럼 당신은 내가 덜 혼란 경우 발견이 작업을 수행 할 수 있지만 정직을 이벤트 핸들러와 같은 일이 양식의 진행률 막대를 업데이트하면 해당 양식에 있습니다. 그렇지 않으면 나중에 (예 : 진행률 표시 줄 문제를 해결하기 위해) 그것을 유지하기 위해, 나는 당신이 그것을 숨긴 곳을 찾기 위해 탐험에 갈 필요가 있습니다.

    그래서 IMO가 뭔가를하는 클래스를 호출하고 해당 클래스가 진행 상태 알림을 반환하면 호출 양식에서 이러한 알림을 처리하는 것이 좋습니다.