我想我的一个 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);
}
}
}
}