Search code examples
c#lambdasignalrsignalr-hub

SignalR core hubconnection lambda action


I have a simple SignalR core hub connection and the hub connection has an On method which takes an action handler I currently have it with a lambda like following but I want to use a event handler so I can unsubscribe it easily and prevent any memory leaks.

hubConnection.On<string, string>(ReceiveMethodKey, (user, message) =>
            {
                var finalMessage = $"{user} says {message}";
                // Update the UI
            });

Solution

  • Using a delegate:

    class MyClass : IDisposable
    {
        private Action<string, string> HubConnectionOnDelegate;
    
        private void InitOrSomething()
        {
            //Pointer to a method, anonymous method, whatever...
            HubConnectionOnDelegate = HubConnection_On;
        }
    
        private static void HubConnection_On(string user, string message)
        {
            var finalMessage = $"{user} says {message}";
            // Update the UI
        }
    
        private void Elsewhere()
        {
            hubConnection.On<string, string>(ReceiveMethodKey, HubConnectionOnDelegate);
        }
    
        public void Dispose()
        {
            HubConnectionOnDelegate = null;
        }
    }