Reputation: 19
Hi all new to C# so apologies upfront I am trying to create an handle in a program to retrieve the string/text and event from this public function in this (websocketwrapper) class.
I have part of the class in question here:
public WebSocketWrapper OnMessage(Action<string, WebSocketWrapper> onMessage)
{
_onMessage = onMessage;
return this;
}
note: _onMessage is declared in the class as:
private Action<string, WebSocketWrapper> _onMessage;
I understand how delegates work and in the process of learning how to use them in actions and event handling but can't work out how to create away to retrieve the result of the above method.
Upvotes: 1
Views: 183
Reputation: 1063884
That pattern is typically used for you to add your own callback, i.e.
server.OnMessage((s, wrapper) => {
Console.WriteLine($"received: {s}");
});
So: whenever a message is received, your callback is invoked and provides the value as s
that is only defined inside the callback lambda. You could also write this as:
server.OnMessage(ProcessMessage);
...
void ProcessMessage(string s, WebSocketWrapper wrapper)
{
Console.WriteLine($"received: {s}");
}
where now the ProcessMessage
method will be invoked whenever a message is received.
Upvotes: 1