[英]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: 一些东西:
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
会处理它,因此您应该没事。) +=
on your assignment to hdl. +=
。 You should just use simple assignment =
. =
。 MyObj.Completed += MyCallbackName
and MyObj.Completed -= MyCallbackName
. MyObj.Completed += MyCallbackName
和MyObj.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.