当我使用 "using" 时,C# 应该关闭流吗?
C# should I close the streams when im using "using"?
我在服务器上有一个压缩文件的服务 运行,我注意到消耗的内存每天都在增加,当我将它部署在服务器上时它消耗了 3.6Mb,今天,3 个月后它消耗了 180Mb。
这是我正在使用的部分代码:
for (i = 0; i < files.Count; i++)
{
try
{
if (File.Exists(@dir + zipToUpdate) && new FileInfo(@dir + zipToUpdate).Length < 104857600)
{
using (FileStream zipToOpen = new FileStream(@dir + zipToUpdate, FileMode.Open))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update, false))
{
if (File.GetCreationTime(@dir + files.ElementAt(i)).AddHours(FileAge) < DateTime.Now)
{
ZipArchiveEntry fileEntry = archive.CreateEntry(files.ElementAt(i));
using (BinaryWriter writer = new BinaryWriter(fileEntry.Open()))
{
using (FileStream sr = new FileStream(@dir + files.ElementAt(i), FileMode.Open, FileAccess.Read))
{
byte[] block = new byte[32768];
int bytesRead = 0;
while ((bytesRead = sr.Read(block, 0, block.Length)) > 0)
{
writer.Write(block, 0, bytesRead);
block = new byte[32768];
}
}
}
File.Delete(@dir + files.ElementAt(i));
}
}
}
}
else
{
createZip(files.GetRange(i, files.Count-i), dir + "\", getZipName(dir, zipToUpdate));
return;
}
}
catch (Exception ex)
{
rootlog.Error(string.Format("Erro Run - updateZip: {0}", ex.Message));
}
}
zip 或更新的创建是相似的,因此没有必要粘贴这两个代码。
我对里面的文件夹进行了递归调用,该服务每小时运行一次。
所以,我的问题是,是否所有这些流都是导致我的内存使用量逐月增加的原因,或者是否可能是其他原因。
using
语句负责关闭它打开的 IDisposable
对象。这不是您观察到的潜在内存泄漏的来源。
我在服务器上有一个压缩文件的服务 运行,我注意到消耗的内存每天都在增加,当我将它部署在服务器上时它消耗了 3.6Mb,今天,3 个月后它消耗了 180Mb。
这是我正在使用的部分代码:
for (i = 0; i < files.Count; i++)
{
try
{
if (File.Exists(@dir + zipToUpdate) && new FileInfo(@dir + zipToUpdate).Length < 104857600)
{
using (FileStream zipToOpen = new FileStream(@dir + zipToUpdate, FileMode.Open))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update, false))
{
if (File.GetCreationTime(@dir + files.ElementAt(i)).AddHours(FileAge) < DateTime.Now)
{
ZipArchiveEntry fileEntry = archive.CreateEntry(files.ElementAt(i));
using (BinaryWriter writer = new BinaryWriter(fileEntry.Open()))
{
using (FileStream sr = new FileStream(@dir + files.ElementAt(i), FileMode.Open, FileAccess.Read))
{
byte[] block = new byte[32768];
int bytesRead = 0;
while ((bytesRead = sr.Read(block, 0, block.Length)) > 0)
{
writer.Write(block, 0, bytesRead);
block = new byte[32768];
}
}
}
File.Delete(@dir + files.ElementAt(i));
}
}
}
}
else
{
createZip(files.GetRange(i, files.Count-i), dir + "\", getZipName(dir, zipToUpdate));
return;
}
}
catch (Exception ex)
{
rootlog.Error(string.Format("Erro Run - updateZip: {0}", ex.Message));
}
}
zip 或更新的创建是相似的,因此没有必要粘贴这两个代码。
我对里面的文件夹进行了递归调用,该服务每小时运行一次。
所以,我的问题是,是否所有这些流都是导致我的内存使用量逐月增加的原因,或者是否可能是其他原因。
using
语句负责关闭它打开的 IDisposable
对象。这不是您观察到的潜在内存泄漏的来源。