Garbage Collector

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gayatri pande
    New Member
    • Jan 2009
    • 10

    Garbage Collector

    What are Weak and Strong References related to Garbage collection procedure?How does it help in performance issues?
  • PRR
    Recognized Expert Contributor
    • Dec 2007
    • 750

    #2
    Data that takes lot of resouce (wrt memory) can be weak referenced (eg large table or dataset)... As long as there is strong reference to it the GC wont collect... when there is no strong reference the GC will free the resource..WeakReference Class (System)

    Comment

    • vekipeki
      Recognized Expert New Member
      • Nov 2007
      • 229

      #3
      Having that in mind, note that WeakReference.T arget can become null at any time (GC runs on a separate thread), so writing something like this:

      Code:
      if (weakReference.Target != null)
         ((SomeClass)weakReference.Target).DoSomething();
      might throw a NullReferenceEx ception if your target gets gollected right after the tested if-expression. Always create a strong reference right before using it:

      Code:
      // create a strong reference to prevent GC from collecting it
      SomeClass object = weakReference.Target as SomeClass;
      if (object != null)
          object.DoSomething();

      Comment

      Working...