Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keeping an object alive in C#

Tags:

c#

I have a class X with large size field member y (in terms of memory) that is declared as static member, I noticed that each time I instantiate an object of X, this field get either loaded or reloaded in the memory. the underlying structure of y is a dictionary<string,int> which holds around 5000 kvs. is there a way to declare y as a separate explicit dictionary an keep it alive during the application life time ?

Notice that: an object of X can be disposed during runtime, so the more accurate question is : if the dictionary is declared as static member of a class, would the static member remains in memory if the the class's object got garbage collected or explicitly destroyed ?

like image 858
Alrehamy Avatar asked Dec 23 '16 22:12

Alrehamy


1 Answers

You are reinstantiating your static field in the instance constructor of the class which is causing the reload/reinstantiation of the dictionary variable. Initialize the static field either in-line where it is declared in the class

static Dictionary<string, int> y = new Dictionary<string, int>() {kvs};

OR

in a static constructor

static Dictionary<string, int> y;
static myClass()
{
    y = new Dictionary<string, int>() {kvs};
}

Static constructor of a class or static field initializers run only once in their life-time.

like image 146
RBT Avatar answered Nov 20 '22 20:11

RBT