Does lambda event subscription create memory leak?
Does this co开发者_JS百科de 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?
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.
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.
If you need to unsubscribe from an event, you need an instanced reference. Unfortunately, that means you can't use that particular syntax.
You'd need to remember the delegate instance you used, like that:
var handler = (s, e) => {};
client.DownloadDataCompleted += handler;
...
client.DownloadDataCompleted -= handler;
精彩评论