简体   繁体   English

如何释放事件处理程序

[英]How to release an event handler

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; 我的问题是: hdl = null; necessary for the latest version of C#? 需要最新版本的C#吗? Also are there any simpler solutions or simpler a syntax for this release? 此发行版还有更简单的解决方案或更简单的语法吗?

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. 简单地将hdl = null设置将不会释放您的处理程序进行垃圾回收,因为MyObj.Completed仍将保留对该处理程序的引用。 (But MyObj.Completed -= hdl takes care of it in this case, so you should be fine.) (但是在这种情况下, MyObj.Completed -= hdl会处理它,因此您应该没事。)
  2. You don't have to use += on your assignment to hdl. 您不必在分配给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 . 如果您的lambda是命名方法,则可以使用MyObj.Completed += MyCallbackNameMyObj.Completed -= MyCallbackName This doesn't work if you need stuff captured in closure, but I don't see that from your example. 如果您需要在闭包中捕获内容,则此方法不起作用,但是我从您的示例中看不到这一点。

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). 擦除变量hdl (实际上是捕获上下文中的一个字段)没有好处(但没有真正的危害)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM