嘿,所以我有一个经常调用的记录器类,有时当它快速重复调用时,它会抛出一个异常,即该文件已打开并被另一个应用程序使用。我们找到解决此问题的唯一方法是捕获异常然后尝试再次打开它......我不确定如何正确处理这个问题。
/// <summary>
/// Open a log file based on a date
/// </summary>
/// <param name="date"> Date of the file to open </param>
public static void OpenLogFile(DateTime date)
{
while (true)
{
try
{
logStream = File.Open("Logs/ems." + date.ToString("yyyy-MM-dd") + ".log", FileMode.Append);
break;
}
catch
{
continue;
}
}
}
/// <summary>
/// Writes to a log file the specified input
/// </summary>
/// <param name="input"> Content to write to the log file </param>
public static void Log(string className, string methodName, string input)
{
OpenLogFile(DateTime.Now);
using (StreamWriter s = new StreamWriter(logStream))
{
s.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + '[' + className + '.' + methodName + "] " + input);
}
CloseLogFile();
}
/// <summary>
/// Closes the current log file
/// </summary>
public static void CloseLogFile()
{
if (logStream != null)
{
logStream.Close();
logStream = null;
}
}