有一个带有事件的简单类:
public class BaseEventProvider {
public event EventHandler SomeEvent;
public void Publish() {
SomeEvent?.Invoke(this, null);
}
}
我知道,如果您使用 lambda 函数处理事件,并且在主要情况下会导致内存泄漏,则很难取消订阅事件。例如:
BaseEventProvider eventProvider = new BaseEventProvider();
eventProvider.SomeEvent += (s, e) => {
Console.WriteLine("was handled!");
};
但是为什么在这种情况下取消订阅有效:
class Program {
static void Main(string[] args) {
BaseEventProvider eventProvider = new BaseEventProvider();
eventProvider.SomeEvent += Handler();
eventProvider.Publish();
eventProvider.SomeEvent -= Handler();
eventProvider.Publish();
Console.ReadKey();
}
private static EventHandler Handler() {
return (s, e) => {
Console.WriteLine("was handled!");
};
}
}
控制台输出显示事件只处理一次:
was handled!
可能在编译和代码优化之后有什么秘密吗?
郎朗坤
相关分类