Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda and memory leaks: Looking for alternative approaches

Tags:

c#

lambda

events

Edit:

I would be greatful if an experienced programmer with the ability to verify this sort of thing showed me the proof that this method is safe from memory leaks. I've been introducing it to many of my coding efforts but I still have a small doubt in my mind. Unfortunately I'm not good enough / don't know the tools to investigate it.

Original:

I learned recently that some uses of lambda expressions can create memory leaks:

    ProjectData Project;

    void OnLaunchNewProject()
    {
        NewProjectUI newProjectUI = new NewProjectUI();
        newProjectUI.OnCompleted += (o, e) =>
            {
                Project = newProjectUI.NewProject;
                view.Content = string.Format("Project {0} was created and saved successfully.", Project.Name);
            };
        newProjectUI.OnCancelled += (o, e) => { view.Content = "Operation was cancelled.";};
        view.Content = newProjectUI;
    }

I learned the bad impact of this method in this blog.

I do not fully understand the impact of referencing local variables in lambda expressions and this limits my ability to circumvent the problem.

Between the typical approach and the use of lambda, what's the ideal compromise? The thing I like about lambda is skipping the definition of the EventHandler's arguments in the body of my class (the sender/routed args) when I don't need them.

like image 964
Joe Avatar asked Feb 19 '23 18:02

Joe


1 Answers

Unfortunately, the blog post you mentioned is wrong. There is not general issue with memory leaks in lambda expressions. In the blog examples, the finalizers are never called because the author never removes the anonymous methods from the event. So the .NET runtime thinks that the method still might be called later and cannot remove the class from memory.

In your code, you will release the NewProjectUI instance somewhere, and this is the point where all events become unsued and when the assigned lambda method also becomes unused. Then the GC can remove the anonymous lambda-helper-class and free the used memory.

So, again: There is no issue in .NET when using local variables in lambda expressions.

But to make your code better, move the code from the lambda expressions to named methods and add these methods to the events. This also makes it possible to remove the methods from the events when they're no longer needed.

like image 60
Carsten Schütte Avatar answered Apr 08 '23 13:04

Carsten Schütte