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 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With