4

I read something about the Weakreference Class in C#, but I´m not sure about the usage of it.

I have a huge table with over 10 or 20k entries. When I write for example a List DBFoos, where Foo are objects from the database.

Where is the advantage of using Weakreference instead of Factory/Singelton Pattern if the user does read only and the pattern is only for the communitation between the classes, because the download of objects takes a while?

Edit

I found an example on MSDN

They use a Weakreference Dictionary like:

public class Cache
{
    // Dictionary to contain the cache.
    public static Dictionary<int, WeakReference> _cache;

If I set in this Cache my Object with the List instead of using a Singelton Like:

public class Foo{
private static Foo foo;
static Foo getreference(){

if(foo == null){
 foo = new Foo();
 return foo;
} 
else 
 return foo;
}
}

Is there any advantage or disatvantage like collecting by the GC with using Weakreference or is it only a complex way of saving it ?

Matthis Kohli
  • 1,877
  • 1
  • 21
  • 23
FoldFence
  • 2,674
  • 4
  • 33
  • 57
  • What do you want to achieve? – Haukinger Jul 12 '16 at 09:04
  • An explanation what and when to use and if possible the advantiges/disatvantiges between these two "patterns" would be nice – FoldFence Jul 12 '16 at 09:14
  • 2
    You are comparing apples and oranges. Those things are unlike the other. Do you have any code where you see those? – Euphoric Jul 12 '16 at 09:28
  • So they were used together? Then why are you asking which one to use? – Euphoric Jul 12 '16 at 09:46
  • Because a static weakreference can be used as the same as a singelton but I´m not sure what to use in this case and why – FoldFence Jul 12 '16 at 09:47
  • 1
    That is not true. Singleton is also using static. And weakreference has nothing to do with it. – Euphoric Jul 12 '16 at 09:50
  • But you can use it as a factory if you use a static variable and link it to a Weakreference so there could be an advantige if its faster or something else or did I miss something ? – FoldFence Jul 12 '16 at 10:55

1 Answers1

1

Weakreference is used to make a cache, you store weakreference in cache to let garbage collector to do is job, so some time you have to reload from database some elements. With Singleton it will make static cache which is not garbaged but if there is enough memory it works fine.

Is there a practical use for weak references?

Community
  • 1
  • 1
Mr_Thorynque
  • 1,749
  • 1
  • 20
  • 31