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?
It doesn’t create a memory leak so long as you don’t hold onto the
WebClientitself – when that’s eligible for garbage collection, the event handler target can be collected too. You typically wouldn’t keep aWebClientaround 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.