gpt4 book ai didi

c# - 释放内存,静态类析构函数?

转载 作者:行者123 更新时间:2023-11-30 13:51:19 25 4
gpt4 key购买 nike

我有一个静态类用作我网站中的数据层。在这个类中,我有字符串数组,用于存储我以后可以访问的查询信息。这是我的类(class)的一部分和有问题的方法:

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;
}
}

这一切都很好,但是通过将断点放在我说的地方,我注意到类成员项目和描述在我的程序(本地 asp 开发服务器)执行之间保留了它们分配的内存和元素。为什么当程序结束时(退出浏览器或停止 Debug模式)这个内存没有被释放?有没有办法手动释放此内存并为静态类创建析构函数?

最佳答案

不,没有静态类的析构函数这样的东西,但是你可以这样做:

public static void Unload() {
items = description = null;
}

关于“程序结束时为什么没有释放此内存”- 如果您的意思是退出浏览器,服务器甚至不会注意到这一点。当应用程序池(在 IIS 中)终止时,它将被清理。

关于c# - 释放内存,静态类析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4684854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com