【发布时间】:2011-01-13 20:24:11
【问题描述】:
我有一个静态类用作我网站中的数据层。在这个类中,我有存储查询信息的字符串数组,我以后可以访问这些信息。这是我的课程的一部分和有问题的方法:
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 开发服务器)执行之间保留了它们分配的内存和元素。为什么程序结束(退出浏览器或停止调试模式)时没有释放此内存?有没有办法手动释放这个内存并为静态类做一个析构函数?
【问题讨论】:
-
顺便说一下,该代码是完全非线程安全的(静态方法通常应该是线程安全的),并且通过返回
items类 -
我对线程一无所知,真的。刚毕业,在 4 年的编程专业中从未提到过多线程.. 对此非常生气
-
这是一个离题但你的代码看起来很糟糕。除非您使用 .NET 1.1,否则将 ArrayList 替换为其通用版本 List
。其次标志变量是无用的。尝试重构代码。还请查看 C# 命名约定,因为您似乎是 Java 开发人员:msdn.microsoft.com/en-us/library/xzf533w0%28v=vs.71%29.aspx -
克里斯是对的。不要被鼓励。将我的评论视为旨在帮助您编写更好代码的建议。事实上,我们每个人都以与您现在相同的方式编写代码,但几年后您会获得经验,这会让您了解应该如何完成。祝你好运!
-
@dzendras - 你的意思是“不要气馁”吗?
标签: c# asp.net memory-management