Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does lambda event subscription create memory leak?

Tags:

c#

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?

like image 607
Jaggu Avatar asked Sep 08 '11 09:09

Jaggu


2 Answers

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.

like image 191
Jon Skeet Avatar answered Nov 08 '22 08:11

Jon Skeet


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;
like image 27
Evgeny Gavrin Avatar answered Nov 08 '22 08:11

Evgeny Gavrin