我有和asp.net mvc 3网站。在本地与web服务器或IIS表示上运行时,它是可以的。但是当在IIS (IIS7.5Windows2008IIS7.5Windows2008 R2)上运行它时,似乎是内存泄漏,因为内存使用量一直在增长。有什么想法吗?
还有一个更新:应用程序中有这样的代码:
SqlConnection conn = new SqlConnection { //creating connection here };
conn.Open();
SqlCommand command = conn.CreateCommand();
try
{
var reader = command.ExecuteReader();
while (reader.Read())
{
//read the data
}
}
finally
{
conn.Close();
}也许应该有类似reader.Dispose的东西?会不会是内存泄漏的原因?
更新:由于某种原因,gc.Collect修复了这个问题。但这并不是出路,因为一直打电话给gc.collect是个坏主意。
发布于 2011-10-28 13:01:24
这里的最佳实践是使用方括号,这是c#的一个很好的特性。当您在括号中使用"using“关键字时,它将在超出括号范围时自动释放已使用的对象。下面是一个例子;
// SqlConnection implements IDisposable, will be disposed after bracket is closed
using(SqlConnection conn = new SqlConnection())
{
conn.Open();
// SqlCommand implements IDisposable, will be disposed after bracket is closed
using(SqlCommand command = conn.CreateCommand())
{
// DataReader implements IDisposable, will be disposed after bracket is closed
using(var reader = command.ExecuteReader())
{
while (reader.Read())
{
// read here.
}
}
}
}这里还有一个微软链接,上面写着“连接在using块的末尾自动关闭”http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.close%28v=VS.85%29.aspx。
希望能帮上忙。
https://stackoverflow.com/questions/7905901
复制相似问题