Print Page | Close Window

Will code like this cause memory leaks?

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2010
Forum Discription: For .NET 4.0
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=3830
Printed Date: 13-May-2026 at 1:01am


Topic: Will code like this cause memory leaks?
Posted By: katit
Subject: Will code like this cause memory leaks?
Date Posted: 30-Nov-2012 at 9:20pm
I noticed in one other place that some of my views in Silverlight weren't disposing because of event subscriptions.
 
Now I'm really paranoid, there is a bunch of code like this laying around:

 var query = this.EntityManager.SYNC_ASTTrailerQuery(trailerKey);

            var op = query.ExecuteAsync();
            op.Completed += (s, args) =>
            {
                if (args.CompletedSuccessfully && onSuccess != null) onSuccess();

                if (!args.HasError) return;
                args.MarkErrorAsHandled();
                if (onFail != null) onFail(args.Error);
            };

            return op;

 
Should I fix it? Is this really going to cause leaks?



Replies:
Posted By: kimj
Date Posted: 03-Dec-2012 at 1:32pm
The code as shown shouldn't cause a memory leak.  The EntityQueryOperation here is short-lived, as is the event handling "subscriber" code.  Memory leaks due to event handlers are said to occur when the publisher of the event lives longer than the subscriber.   Here, the operation is the publisher, and if you aren't holding on to the returned EntityQueryOperation, shouldn't cause a leak.   That said, the best way to determine if your application has leaks is to profile it.


Posted By: mgood
Date Posted: 03-Dec-2012 at 4:44pm
Unfortunately, memory leaks also occur if the subscriber lives longer than the publisher. With a .NET event both subscriber and publisher hold a strong reference to each other unless the subscriber is static. The above code is safe due to the use of a locally scoped lamba. It would be problematic if you made the event handler an instance method of the current class. In that case the EntityQueryOperation couldn't be garbage collected until your current class instance goes away.



Print Page | Close Window