Events Handling as Culprit to Memory Leakage - A Developer Must Care about it



Memory Leakage in applications are most common and a developer maximum time does not care about it. There are various possibilities for Memory leakage and one of them is Events registered in applications which a developer unknowingly forgets to handle.

 

So, what are the cases where that could make problem and are there any proper solutions to tackle down this issue? Let us discuss on this topic today.

 

It’s a common mistakes by many developers, either they don’t know about such possibilities in their applications or they just ignore/forget to take care of events. Let’s begin with a real time scenario.

 

Suppose you built an awesome application and tested it properly from your end, fixed various issues related to functionalities and UI issues. You also verified your app from a tester and received green signal to deploy the app to the client’s PC, mobile or any other targeted environment. You became happy deploying the app with almost zero bugs.

 

Now after few days the users reported to you saying that, they are facing a lot of issues after installing your application. That will generally come to you as a thunderstorm and you will start asking the users to check the system configuration without first checking your app.

Event Registration in Memory

 

Later you will start tracing the app and come to know that, the application is taking a huge memory than expected and that is increasing time to time because the user is opening some window of your app, closing and reopening multiple times. Sometime the application is malfunctioning and retaining the previous values though the Window inside the app is closed.

 

The big boss is there and started shouting on you because he noticed some memory leaks in your application that you coded. There could be various possibilities to check it out for such memory leaks and one of them is event handling. You started searching for such possibilities in your code and noticed that you or your team member subscribed for various events and many of those events are registering multiple times in the life time of the screen. You also noticed that they were not removed after the completion of actual operation. Thus it’s keeping a strong reference to the object though the window has been closed or hidden.

 

Problem and Solution

As a developer we should take care of such event handling mechanism from the very beginning wen we start working on something by registering events. This is a common scenario in almost all of the XAML technologies we work for (e.g. Silverlight, WPF, Windows Phone or Windows 8 RT applications etc.), when we register the event but don’t care about deregistering it from memory. Sometime it becomes even painful when multiple registration happens without removing the first instance of the same. Thus your application starts misbehaving some cases and increasing the memory uses.

 

As there are strong reference to the memory locations present, Garbage Collector does not go for collecting objects those are no longer used.

 

For example, the below code may produce memory leakage:

 
protected void OnUpdateClick(object sender, EventArgs args)
{
    context.SubmitOperationCompleted += OnSubmitOperationCompleted;
    context.Submit(accountDetails);
}
 
protected void OnSubmitOperationCompleted(object sender, SubmitCompletedEventArgs e)
{
    MessageBox.Show("Account has been updated");
}

 

 

In the above scenario, as we are subscribing to the submit operation completed event on click on update button and before calling the actual submit method, this may occur multiple times. As we are not removing the reference from memory on successful completion, this may create memory leakage because of multiple event registration.

 

This could be easily resolved by removing the event from memory on completion of the completed event implementation and that would pay you less buggy code. Here is a simple example of that:

 

 
protected void OnUpdateClick(object sender, EventArgs args)
{
    context.SubmitOperationCompleted += OnSubmitOperationCompleted;
    context.Submit(accountDetails);
}
 
protected void OnSubmitOperationCompleted(object sender, SubmitCompletedEventArgs e)
{
    // first remove the event registration from memory
    context.SubmitOperationCompleted -= OnSubmitOperationCompleted;
    MessageBox.Show("Account has been updated");
}

 

 

That will free up the strong reference and if we do this for all of the event registration, there will be almost zero buggy code of strong unnecessary references in the code.

 

Yes, it’s not 100% sure that it will completely remove the memory leakage from your application but will remove max of them. There could be other possibilities too, but let’s discuss that sometime in another post.

 

If you had faced similar issues earlier in your code, share your experience with the other developer community members and help them (mainly the new comers) to know about this and your experience. You wanted to say something that I missed? Please drop a line below.

4 comments

  1. Hi Kunal,
    I have already done this. I have unregistered all events, but still its not working for me. I am using Silverlight.
    Please provide a solution for this can you give your email id?.

    ReplyDelete
    Replies
    1. Hi Abhinav,

      Memory Leakage not only depends on events. There are some more parameters like strong reference, object reference etc. which takes call on this too. Events are just a single parameter. You have to check all other references.

      Regards,
      Kunal

      Delete
  2. Is this Memory Leakage problem persist with BackgroundWorker as well ? If Yes then do we need to handle it for all -= func_DoWork, -= func_RunWorkerCompleted, other if available ?

    ReplyDelete
    Replies
    1. It's always a better idea to remove when not require.

      Delete


 
© 2008-2014 Kunal-Chowdhury.com | Designed by Kunal Chowdhury
Back to top