【发布时间】:2020-02-04 22:14:47
【问题描述】:
我有一个应用程序,它使用OpenXmlPowerTools 从 .docx 文件中读取 cmets 和段落。它是一个控制台应用程序,它在运行时会创建一个 debug.log 文件。
实现了一个记录器类,它将消息保存到所有构建的文本文件中,并将这些消息打印到控制台以进行调试构建。以下代码是该记录器类的一部分:
public static class Logger
{
public enum LogLevel
{
ERROR, WARNING, DEBUG
}
public static void Log(string message, LogLevel level, bool newline)
{
try
{
// the very next line was a hotspot, as shown in the profiler
using (StreamWriter sw = File.AppendText(path))
{
// write the messages to this file
}
}
catch (Exception ex)
{
// handle it
// I know it is bad practice to catch System.Exception, I need to fix this.
}
}
}
在代码中,这个函数经常被这样调用:
private void doSomething(string someParameter)
{
Logger.Log("The parameter is: " + someParameter, Logger.LogLevel.DEBUG, true);
}
我已经分析了它的性能,对于一个包含几十个 cmets 的相当大的 word 文档,它需要 1 分 40 秒才能完成。没有记录,只需要几秒钟。经过一番调查,似乎File.AppendText 在.NET 中非常慢。
作为替代方案,我尝试使用缓冲区:
using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8, 65536)
{
// write the messages to the file
}
与我读过的推荐这种方法的文章中的信息相反,性能似乎变差了(耗时超过 2 分钟)。为什么是这样?我怎样才能提高它的性能?
【问题讨论】:
标签: c# .net file logging streamwriter