简体   繁体   中英

Record and replay raised events in VB.NET

I implemented the communication between two classes by using events in VB.NET. Now I want to store (record) all events that occurred and to re-raise (replay) them again later.

Here is what I have already:

Class1:

Public Event Button1Pressed(ByVal sender As Object)

Private Sub btnButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnButton.Click
    RaiseEvent Button1Pressed(Me)
End Sub

Public Sub handleDisplayChanged(ByVal sender As System.Object, ByVal txt As String)

        '... Some code
End Sub

Class 2:

Public Event DisplayTextChangedEvent(ByVal sender As System.Object, ByVal text As String)

'In the constructor:
AddHandler Me.DisplayTextChangedEvent, AddressOf class1Instance.displayText
AddHandler class1Instance.Button1Pressed, AddressOf Me.buttonPressed

'Somewhere in the logic:
Public Sub buttonPressed(ByVal sender As Object)

    'Compute text
    '...
    RaiseEvent DisplayTextChangedEvent(text)
End Sub

I could add another handler to the event I want to record, but then in the handler I only get the parameters that are passed to the event and not the event itself. Another thing I don't know how to solve is, that I can't raise an event from an extern class.

Is there a good solution for my problem?

To record the event, you can make an auxiliary method that does the recording AND the raising. So instead of this:

RaiseEvent Button1Pressed(Me)

do this:

Sub RaiseButton1PressedEvent()
  RaiseEvent Button1Pressed(Me)  <--raise the event

  RecordEvent("Button1Pressed")  <--record the event
End Sub

What RecordEvent does has to be designed, of course.

To raise the event from an external class, implement this method:

Sub ReplayButton1PressedEvent()
  RaiseEvent Button1Pressed(Me)  <--raise the event
End Sub

Now, if you have a lot of events, this could get tedious. There are a couple of nice ways to address this:

  1. There's probably a way to raise an event using reflection, based on the name of the event, so you could implement one generic function instead of one for each event, that is: instead of Sub RaiseButton1PressedEvent() , you could have a Sub RaiseEventByName(sEventName As String)

  2. Use code generation to emit a partial class with Raise and Replay methods for each of the events you want to track.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM