gpt4 book ai didi

c# - 识别内存泄漏

转载 作者:行者123 更新时间:2023-11-30 20:59:00 25 4
gpt4 key购买 nike

我想我的一个 C# 可执行文件(它是一个控制台应用程序)存在严重的内存泄漏。内存大小不断增加和超时我需要重新启动应用程序以降低内存使用量。我正在使用 FileSystemWatcher,然后当文件可用时将其拾取并将其转换为 utf-8 并转发它。然后向控制台写入文件此时正在处理。因此它会在每次处理时写入控制台。

我正在使用 Ants 内存分析器,并且刚开始使用它时还很新鲜。我无法用它弄清楚。当我拍摄内存快照时,它会显示:

namespace:System, Classname: byte[] --- 每次处理文件并在控制台上显示它时都会增加(增加 40,000 字节)并且永远不会返回。

这是正确的吗?

更新:

class Class1
{
private static FileSystemWatcher watcher = new FileSystemWatcher();

public static void Main()
{
WatchFile();
Console.ReadLine();
}

private static void WatchFile()
{
watcher.Path = @"N:\";
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "*.xml";
watcher.Changed += new FileSystemEventHandler(convert);
watcher.Error += new ErrorEventHandler(WatcherError);
watcher.EnableRaisingEvents = true;

Console.WriteLine("Press \'q\' to quit.");

while (Console.Read() != 'q');
}

public static string CrL = "\r\n";

private static object lockObject = new object();

private static void convert(object source, FileSystemEventArgs f)
{
string FileName;
FileName = f.FullPath;

string destinationFile = @"F:\test.xml";

Thread.Sleep(2000);
if (!Monitor.TryEnter(lockObject))
{
return;
}
try
{
watcher.EnableRaisingEvents = false;
Thread.Sleep(2000);

var doc = new XmlDocument();
doc.Load(FileName);

XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true };

using (var writer = XmlWriter.Create(destinationFile, settings))
{
doc.Save(writer);
}

Console.WriteLine("File Copied" + " " + DateTime.Now.ToString("HH:mm:ss tt"));
Console.WriteLine("Press \'q\' to quit.");
Console.Write(CrL);
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally
{
Monitor.Exit(lockObject);
watcher.EnableRaisingEvents = true;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}

private class Utf8StringWriter : StringWriter
{
public override Encoding Encoding { get { return Encoding.UTF8; } }
}

private static void WatcherError(object source, ErrorEventArgs e)
{
Exception watchException = e.GetException();
watcher = new FileSystemWatcher();
while (!watcher.EnableRaisingEvents)
{
try
{
WatchFile();
Console.WriteLine("I'm Back!!");
}
catch
{
Thread.Sleep(2000);
}
}
}
}

最佳答案

这里有类似的问题 - Memory leak while using Threads

据我对解决方案的了解,写入控制台并使用 Thread.Sleep 是问题所在。

此外,也许适用(或不适用)- http://support.microsoft.com/kb/2628838

从此处下载修补程序(Framework 4.0 的可靠性更新 2)文件 - http://support.microsoft.com/kb/2600217

关于c# - 识别内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15698203/

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