Lambda and memory leaks: finding alternative approaches

Edit:

It would be great if an experienced programmer with the ability to check such things showed me proof that this method is protected from memory leaks. I tell this to many of my coding efforts, but I still have little doubt in my mind. Unfortunately, I am not good enough / do not know the tools for research.

Original:

I recently learned that some uses of lambda expressions can cause 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 found out about the bad influence of this method on this blog .

I do not quite understand the effect of referencing local variables in lambda expressions, and this limits my ability to get around the problem.

Between the typical approach and using lambda, what is the perfect compromise? What I like about lambda skips the definition of EventHandler arguments in the body of my class (senders / redirected arguments) when I don't need them.

+4
source share
1 answer

Sorry, the blog post you were talking about is incorrect. Lambda expressions do not have a common problem with memory leaks. In the blog examples, finalizers are never called because the author never removes anonymous methods from the event. Therefore, the .NET runtime believes that the method can still be called later and cannot remove the class from memory.

In your code, you will select an instance of NewProjectUI somewhere, and this is the moment when all events become unsuccessful and when the assigned lambda method also becomes unused. GC can then remove the anonymous lambda helper class and free up used memory.

So, again: in .NET there is no problem using local variables in lambda expressions.

But to make the code better, move the code from lambda expressions to named methods and add these methods to events. It also allows you to remove methods from events when they are no longer needed.

+8
source

Source: https://habr.com/ru/post/1440971/


All Articles