SignalR核心集线器连接lambda动作

时间:2019-02-21 21:16:45

标签: c# lambda signalr signalr-hub

我有一个简单的SignalR核心集线器连接,并且集线器连接具有一个On方法,该方法需要一个动作处理程序,我目前使用的lambda如下所示,但是我想使用事件处理程序,因此可以取消订阅轻松并防止任何内存泄漏。

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

1 个答案:

答案 0 :(得分:0)

使用委托人:

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;
    }
}