0

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?

2 Answers 2

0

A few things:

  1. Simply setting hdl = null will not free your handler for garbage collection because MyObj.Completed would still hold the reference to the handler. (But MyObj.Completed -= hdl takes care of it in this case, so you should be fine.)
  2. You don't have to use += on your assignment to hdl. You should just use simple assignment =.
  3. If your lambda were, instead, a named method, you could use MyObj.Completed += MyCallbackName and MyObj.Completed -= MyCallbackName. This doesn't work if you need stuff captured in closure, but I don't see that from your example.
0

No, it is not required. That is basically all tied to a capture-context (compiler-generated class); once the event is unsubscribed, nothing will be keeping the capture-context in scope, so it will be eligible for garbage collection. There is no benefit (but no real harm) wiping the variable hdl (actually a field on the capture-context).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.