Event unsubscription via anonymous delegate [duplicate]

时光总嘲笑我的痴心妄想 提交于 2020-01-01 01:35:29

问题


I am using Resharper 5.1 code analysis many a times i get a comment from resharper as

"Event unsubscription via anonymous delegate"

#Part of Code  

if (((bool)e.NewValue))
{
    listView.PreviewTextInput += (o,args) =>
        listView_PreviewTextInput(o,args,listView);
}
else
{
    listView.PreviewTextInput -= (o, args) => 
        listView_PreviewTextInput(o, args, listView);
}

How could i correct or optimze this thing


回答1:


You can extract the lamdba to a variable:

EventHandler func = (sender, e) =>
    listView_PreviewTextInput(sender, e, listView);

if (((bool)e.NewValue))
{
    listView.PreviewTextInput += func;
}
else
{
    listView.PreviewTextInput -= func;
}



回答2:


Warning! Accepted answer from Steven is wrong, all it does is just masking a problem that resharper is warning about.

Every time given code is executed

 EventHandler func = (sender, e) =>
     listView_PreviewTextInput(sender, e, listView);

you'll get a fresh (since you may capture different listView) instance of anonymous delegate saved to func, an instance that's not subscribed to any events yet, so in turn this code

listView.PreviewTextInput -= func;

will effectively do nothing, since you cant unsubscribe from an event you're not subscribed to. This will lead to mind-boggling bugs like event handlers 'called twice', memory leaks etc.

Actually, Jon Skeet says it may work in some cases:

The C# specification explicitly states (IIRC) that if you have two anonymous functions (anonymous methods or lambda expressions) it may or may not create equal delegates from that code.

e.g. when compiler doesn't generate new instance every time, you'll see nice behavior.

But that's not reliable and certainly wouldn't work in case described in starter question with captured variable listView.

So my suggestion is:

Use anonymous functions as event handlers ONLY if you will never have to unsubscribe.



来源:https://stackoverflow.com/questions/8803064/event-unsubscription-via-anonymous-delegate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!