Nic*_*ndo 3 c# asp.net memory-management
我有一个静态类,我在我的网站中用作我的数据层.在这个类中,我有一个字符串数组,用于存储我以后可以访问的查询信息.这是我班级和问题方法的一部分:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这一切都很好,但是通过把断点放在我说的地方,我注意到类成员项和描述在我的程序(本地asp开发服务器)的执行之间保留了它们分配的内存和元素.为什么程序结束时退出(从浏览器退出或停止调试模式),这个内存不会被释放?有没有办法手动释放这个内存并为静态类创建一个析构函数?
不,没有静态类的析构函数,但你可以这样做:
public static void Unload() {
items = description = null;
}
Run Code Online (Sandbox Code Playgroud)
Re"当程序结束时为什么不释放这个内存" - 如果你的意思是退出浏览器,服务器甚至都不会注意到.当应用程序池(在IIS中)死亡时,它将被清除.