Reputation: 3464
I have an object that, on startup, requests some information from a server. It sends an identifier with the message which will be the same on the reply, so it can be sure that it's responding to the right message. Currently, the code looks roughly like this.
void GetInitialData()
{
string guid = Guid.NewGuid().ToString();
Communicator.NewMessage += (sender, e)
{
if(e.Message.Id == guid)
FillInfo();
};
Communicator.SendMessage(new Message(stuff, guid));
}
This works, but as this data is only needed once, I'd like to unsubscribe from the event afterwards, which you can't do with a lambda. If I use a separate function instead, this allows me to unsubscribe, but it seems that the only way to pass the parameter to the function is through a class variable.
string guid;
void GetInitialData()
{
Communicator.NewMessage += MessageReceived;
Communicator.SendMessage(new Message(stuff, guid));
}
void MessageReceived(object sender, MessageArgs e)
{
if(e.Message.Id == guid)
{
FillInfo();
Communicator.NewMessage -= MessageReceived;
}
}
Is there a way around this that will let me unsubscribe and also avoid cluttering up the class with extra variables?
Upvotes: 3
Views: 218
Reputation: 172606
You can deregister the lambda when you store it in a variable first:
void GetInitialData()
{
EventHandler<EventArgs> handler = null;
handler = (sender, e) =>
{
if(e.Message.Id == guid)
{
FillInfo();
Communicator.NewMessage -= handler;
}
};
string guid = Guid.NewGuid().ToString();
Communicator.NewMessage += handler;;
Communicator.SendMessage(new Message(stuff, guid));
}
Upvotes: 4