是否拉姆达事件订阅创建内存泄漏? [英] Does lambda event subscription create memory leak?

查看:139
本文介绍了是否拉姆达事件订阅创建内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码是否创建一个内存泄漏

Does this code create a memory leak?

WebClient client = new WebClient();

client.DownloadDataCompleted += (sen, args) => {

};
client.DownloadData("http://foo.bar");



由于没有办法实际从事件退订。我可以说,我们绝不能使用事件订阅拉姆达?

As there is no way to actually unsubscribe from the event. Can I say we must never use lambda for event subscription?

推荐答案

它不创建一个内存泄漏,只要你不'T稳守 Web客户端本身时 - 这是符合垃圾收集,事件处理程序的目标可以被收集了。通常,您的不会的保持 Web客户端很长一段时间 - 他们通常用作一次性物品

It doesn't create a memory leak so long as you don't hold onto the WebClient itself - when that's eligible for garbage collection, the event handler target can be collected too. You typically wouldn't keep a WebClient around for a long time - they're typically used as one-shot objects.

此外,该lambda表达式没有使用任何变量从这个,所以它可能会与没有目标的静态方法来实现反正...我承担的真正的情况下,你很关心的还有一个更有趣的lambda身体。

Additionally, that lambda expression isn't using any variables from this, so it would probably be implemented by a static method with no target anyway... I assume the real situation you're concerned with has a more interesting lambda body.

这篇关于是否拉姆达事件订阅创建内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆