deallocating memory, static class destructor?
I have a static class I'm using as my data layer in my website. In this class, I have string arrays that store queried information that I can access later. Here's the part of my class and the method in question:
public static class data_layer
{
private static string[] items;
private static string[] description;
//will return description for an item id. if no item id is found, null is returned
public static string getDesc(string key)
{
int i = 0;
bool flag = false;
//search for the item id to find its index
for(i = 0; i < items.Length; i++)
{
if(items[i] == key)
{
flag = true;
break;
}
}
if(flag)
return description[i];
else
return null;
}
public static string[] getItems()
{
return items;
}
public static bool setItemsAndDescriptions()
{
ArrayList itemIDs = new ArrayList();
ArrayList itemDescs = new ArrayList();
SqlConnection sqlConn = new SqlConnection();
sqlConn.ConnectionString = ConfigurationManager.ConnectionStrings["MAS200RAWConnectionString"].ConnectionString;
string query = "SELECT ItemNumber, ItemDescription FROM OUS_IM1_InventoryMasterfile " +
"WHERE ItemNumber LIKE 'E%' OR ItemNumber LIKE 'B%' OR ItemNumber LIKE 'D%'";
try
{
sqlConn.Open();
SqlCommand sqlComm = new SqlCommand();
sqlComm.Connection = sqlConn;
sqlComm.CommandType = CommandType.Text;
sqlComm.CommandText = query;
SqlDataReader reader = sqlComm.ExecuteReader();
if (reader == null)
return false;
//add the queried items to the ddl
while (reader.Read())
{
itemIDs.Add(reader["ItemNumber"].ToString().Trim());
itemDescs.Add(reader["ItemDescription"].ToString().Trim());
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
sqlConn.Close(); //NOTE: I HAVE A BREAKPOINT HERE FOR DUBUGGING
}
items = itemIDs.ToArray(typeof(string)) as string[];
description = itemDescs.ToArray(typeof(string)) as string[];
return true;
}
}
This all works fine, but by putting the breakpoint where I said I put it, I noticed that the class members items and description retain their allocated memory and elements between executions of my program (local a开发者_运维技巧sp dev server). Why is this memory not getting released when the program ends (exiting out of the browser or stopping debug mode)? Is there a way to manually release this memory and make a desctructor for a static class?
No, there's no such thing as a destructor for a static class, but you can do something like:
public static void Unload() {
items = description = null;
}
Re "Why is this memory not getting released when the program ends" - if you mean exiting the browser, the server won't even notice that. It will get cleaned when the app-pool (in IIS) dies.
It's because the fields are static and stopping debugging doesn't mean the WebDev server is shut down. If you want to store the strings per user, put them in session object. It guarantees that they will be available per user, and will be forgotten once session ends (timeout or closing the browser window).
精彩评论