New Posts New Posts RSS Feed: Will code like this cause memory leaks?
  FAQ FAQ  Forum Search   Calendar   Register Register  Login Login

Will code like this cause memory leaks?

 Post Reply Post Reply
Author
mgood View Drop Down
IdeaBlade
IdeaBlade
Avatar

Joined: 18-Nov-2010
Location: Emeryville, CA
Posts: 583
Post Options Post Options   Quote mgood Quote  Post ReplyReply Direct Link To This Post Topic: Will code like this cause memory leaks?
    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.
Back to Top
kimj View Drop Down
IdeaBlade
IdeaBlade
Avatar

Joined: 09-May-2007
Posts: 1391
Post Options Post Options   Quote kimj Quote  Post ReplyReply Direct Link To This Post 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.
Back to Top
katit View Drop Down
Senior Member
Senior Member


Joined: 09-Sep-2011
Posts: 146
Post Options Post Options   Quote katit Quote  Post ReplyReply Direct Link To This Post 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?
Back to Top
 Post Reply Post Reply

Forum Jump Forum Permissions View Drop Down