How do I Unregister 'anonymous' event hand

2020-01-24 12:37发布

Say if I listen for an event:

Subject.NewEvent += delegate(object sender, NewEventArgs e)
{
    //some code
}); 

Now how do I un-register this event? Or just allow the memory to leak?

7条回答
你好瞎i
2楼-- · 2020-01-24 13:10

There is another question (of mine) which goes into this in some (too much) detail: Weak event handler model for use with lambdas.

However, now that the Reactive Framework has come out, I'd seriously consider looking into that in this kind of situation.

查看更多
我只想做你的唯一
3楼-- · 2020-01-24 13:12

To remove the handler on first invocation:

//SubjectType Subject = ..... already defined if using (2)

EventHandler handler = null;
handler = delegate(object sender, EventArgs e)
{
    // (1)
    (sender as SubjectType).NewEvent -= handler;
    // or
    // (2) Subject.NewEvent -= handler;

    // do stuff here
};

Subject.NewEvent += handler;
查看更多
叼着烟拽天下
4楼-- · 2020-01-24 13:22

If you need to unregister an event, I recommend avoiding anonymous delegates for the event handler.

This is one case where assigning this to a local method is better - you can unsubscribe from the event cleanly.

查看更多
放荡不羁爱自由
5楼-- · 2020-01-24 13:23

Give your instance of the anonymous delegate a name:

EventHandler<NewEventArg> handler = delegate(object sender, NewEventArgs e)
{
    //some code
};

Subject.NewEvent += handler;
Subject.NewEvent -= handler;
查看更多
小情绪 Triste *
6楼-- · 2020-01-24 13:23

Do you need to un-register it for a reason other than leakage?

Regarding the "Or just allow the memory to leak" bit, when Subject is cleaned up by the Garbage Collector, your anonymous delegate should be cleaned up as well, so there shouldn't be a leak.

查看更多
Melony?
7楼-- · 2020-01-24 13:31

You need a name for your anonymous function, and then, you can only do it as long as the name is in scope:

    var handler = new EventHandler(delegate(object o, EventArgs e)
    {
        //do something...
    };

    Subject.NewEvent += handler;

    // later on while handler is still in scope...

    Subject.NewEvent -= handler;
查看更多
登录 后发表回答