By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,988 Members | 1,074 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,988 IT Pros & Developers. It's quick & easy.

Garbage Collector

P: 10
What are Weak and Strong References related to Garbage collection procedure?How does it help in performance issues?
Jan 22 '09 #1
Share this Question
Share on Google+
2 Replies


Expert 100+
P: 750
PRR
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)
Jan 22 '09 #2

vekipeki
Expert 100+
P: 229
Having that in mind, note that WeakReference.Target can become null at any time (GC runs on a separate thread), so writing something like this:

Expand|Select|Wrap|Line Numbers
  1. if (weakReference.Target != null)
  2.    ((SomeClass)weakReference.Target).DoSomething();
might throw a NullReferenceException if your target gets gollected right after the tested if-expression. Always create a strong reference right before using it:

Expand|Select|Wrap|Line Numbers
  1. // create a strong reference to prevent GC from collecting it
  2. SomeClass object = weakReference.Target as SomeClass;
  3. if (object != null)
  4.     object.DoSomething();
  5.  
Jan 22 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.