Normally, anonymous event handlers can be released as follows:
EventHandler hdl = null;
hdl += (ss,ee) =>
{
//....
MyObj.Completed -= hdl;
hdl = null;
};
MyObj.Completed += hdl;
MyObj.AsyncCall();
My question is: Is hdl = null; necessary for the latest version of C#? Also are there any simpler solutions or simpler a syntax for this release?
A few things:
hdl = nullwill not free your handler for garbage collection because MyObj.Completed would still hold the reference to the handler. (ButMyObj.Completed -= hdltakes care of it in this case, so you should be fine.)+=on your assignment to hdl. You should just use simple assignment=.MyObj.Completed += MyCallbackNameandMyObj.Completed -= MyCallbackName. This doesn’t work if you need stuff captured in closure, but I don’t see that from your example.