• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1075
  • Last Modified:

Will Action/Func causes memory leak when stored as member reference inside another class?

Hi experts
I am passing a method into another class which stores this method as a member reference and Property method. Will these cause memory leak?

public class KeepReference
{
     private Action _callBackMethod1;
     public KeepReference(Action aMethod)
     {
          _callBackMethod1 = aMethod;
     }

     public Action CallBackMethod2 {get; set;}
}

public class CallingClass
{
      public void abc()
      {
                :
            KeepReference kkk = new KeepReference(CallBackMethod);  // memory leak?
                :
            kkk.CallBackMethod2 = CallBackMethod; // memory leak?

      }

      private void CallBackMethod()
      {...}
}

Open in new window


Thanks.
0
dominicwong
Asked:
dominicwong
  • 3
  • 2
2 Solutions
 
anarki_jimbelCommented:
Is it causing?

For me it looks pretty OK. However, referenced class won't be garbage collected unless you either:

 - destroy the current object
 - destroy the reference (set to null)
0
 
dominicwongAuthor Commented:
Not sure whether it is leaking memory.
But for normal delegates using "+=", the caller has to explicitly call "-=" in order to avoid memory leak. In my case, I use the delegate "Action" and that makes me ponder if I need to do similar thing in order to avoid memory leak.
0
 
käµfm³d 👽Commented:
What is your idea of a "memory leak?"
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
dominicwongAuthor Commented:
The memory leak that I am concerned about is that it is not released by garbage collector.
0
 
käµfm³d 👽Commented:
Then I agree with anarki_jimbel, though in this case all the references are destroyed once abc returns (since you have declared everything local to the method).
0
 
dominicwongAuthor Commented:
Thanks anarki_jimbel and kaufmed for your prompt responses.
0

Featured Post

Take Control of Web Hosting For Your Clients

As a web developer or IT admin, successfully managing multiple client accounts can be challenging. In this webinar we will look at the tools provided by Media Temple and Plesk to make managing your clients’ hosting easier.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now