VB.NET 2008/VB - 이벤트

이벤트 처리 - 블로킹을 방지하는 이벤트 선언

본클라쓰 2011. 4. 17. 11:03

특정 이벤트 처리기가 후속 이벤트 처리기를 차단하지 않아야 하는 경우가 많이 있다. 이 때 사용자 지정 이벤트를 사용하면 이벤트가 해당 이벤트 처리기를 비동기적으로 호출할 수 있다.

 

기본적으로 이벤트 선언에 대한 지원 저장소 필드는 모든 이벤트를 순차적으로 사용하는 멀티캐스트 대리자이다. 즉, 특정 처리기가 완료하는 데 시간이 오래 걸릴 경우 해당 처리기가 완료될 때까지 다른 처리기를 차단한다. 그러나 올바르게 동작하는 이벤트 처리기는 수행하는 데 시간이 오래 걸리는 작업이나 다른 작업을 차단하는 작업을 수행하지 않는다.

 

다음 예제에서 AddHandler 접근자는 Click 이벤트의 각 처리기에 대한 대리자를 EventHandlerList 필드에 저장된 ArrayList에 추가한다.

 

코드가 Click 이벤트를 발생시키면 RaiseEvent 접근자는 BeginInvoke 메서드를 사용하여 모든 이벤트 처리기 대리자를 호출한다.

 

Public NotInheritable Class ReliabilityOptimizedControl

    'Defines a list for storing the delegates
    Private EventHandlerList As New ArrayList

    'Defines the Click event using the custom event syntax.
    'The RaiseEvent always invokes the delegates asynchronously
    Public Custom Event Click As EventHandler
        AddHandler(ByVal value As EventHandler)
            EventHandlerList.Add(value)
        End AddHandler
        RemoveHandler(ByVal value As EventHandler)
            EventHandlerList.Remove(value)
        End RemoveHandler
        RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
            For Each handler As EventHandler In EventHandlerList
                If handler IsNot Nothing Then
                    handler.BeginInvoke(sender, e, Nothing, Nothing)
                End If
            Next
        End RaiseEvent
    End Event
End Class