Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I redirect events in .NET?

Tags:

.net

events

I've got a class which is catching the System.Diagnostics.DataReceivedEventArgs event.

I want to make this event externally available. To accomplish that currently I'm catching this internally and raising another event, which seems like a bit duplication to me.

What's the best way to this? Can I wire these events so I do not need to raise a new event?

Here is the code :

Class MyClass  

Public Event OutputDataReceived(sender As Object, e As System.Diagnostics.DataReceivedEventArgs)

Public Sub Action()
    ....
     AddHandler Process.OutputDataReceived, AddressOf ReadData
    ....
End Sub

  Private Sub ReadData(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs)
        RaiseEvent Me.OutputDataReceived(sender, e)
    End Sub

End Class
like image 708
dr. evil Avatar asked Dec 13 '25 19:12

dr. evil


1 Answers

What do you mean by "catching" the event? One thing you can do is expose your own event, which just passes on subscriptions/unsubscriptions to the other one:

public event DataReceivedEventHandler DataReceived
{
    add
    {
        realEventSource.DataReceived += value;
    }
    remove
    {
        realEventSource.DataReceived -= value;
    }
}

For more details on events, read my article on the topic - let me know if anything's unclear.

EDIT: Here's the equivalent in VB.NET:

Public Custom Event DataReceived As DataReceivedEventHandler
    AddHandler(ByVal value As DataReceivedEventHandler)
        AddHandler Me.realEventSource.DataReceived, value
    End AddHandler
    RemoveHandler(ByVal value As DataReceivedEventHandler)
        RemoveHandler Me.realEventSource.DataReceived, value
    End RemoveHandler
    RaiseEvent(ByVal sender as Object, ByVal args as DataReceivedEventArgs)
        Throw New NotSupportedException
    End RaiseEvent
End Event
like image 195
Jon Skeet Avatar answered Dec 16 '25 23:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!