简体   繁体   中英

C# - SignalR How can I remove my event handler

I am a C# newbie trying to implement SignalR in my Xamarin IOS app.

My code is quite simple:

 _connection = new Microsoft.AspNet.SignalR.Client.Hubs.HubConnection (Common.signalRAddress);

feedHub = _connection.CreateHubProxy ("feedHub");

_connection.Received += data =>  { OnReceiveData (data); };

_connection.Start ();   

my question is how can I remove my delegate? Is it enough to write?

_connection.Received -= data =>  { OnReceiveData (data); };

Any help would be really appreciated.

You're using a hub, why not use the built in on/off for method invocations?

aka:

var doSomething = feeHub.On<int>("doSomething", val => {
    // Do something with int val
});

Then to remove it you can do:

doSomething.Dispose();

If you truly want to listen to ALL data that flows through the hub then using Received is the correct approach and @Dracanus' answer will work.

I might be wrong, but if you do that it won't actually unsubscribe the event.

It didn't in a little test app I wrote anyways.

Instead create a function such as

void Connection_Recieved(string obj)
{
}

and do connection.Recieved += Connection_Recieved; and connection.Recieved -= Connection_Recieved;

I don't think anonymous event functions are the way to go here :)

I am assuming, looking at your code sample you could just do,

   connection.Recieved += OnReceiveData;
   connection.Recieved -= OnReceiveData;

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