【发布时间】:2010-06-20 23:24:04
【问题描述】:
这是我的自定义“记录器”类,它可以帮助我在项目中创建日志文件。
namespace MyProject
{
class Logger
{
private FileInfo fFile;
private DirectoryInfo dDir;
/// <summary>Add a new entry to the log file.</summary>
/// <param name="sData">The line to add.</param>
public void Add(string sData)
{
DateTime CurrTime = DateTime.Now;
if (fFile.Length > 1048576)
{
fFile.MoveTo(Path.Combine(dDir.FullName, CurrTime.ToShortDateString() + fFile.Name));
fFile = new FileInfo(Path.Combine(dDir.FullName,fFile.Name));
using (StreamWriter sw = fFile.CreateText())
{
sw.WriteLine("{0:u}|{1}", CurrTime, sData);
}
}
else
{
using (StreamWriter sw = fFile.AppendText())
{
sw.WriteLine("{0:u}|{1}", CurrTime, sData);
}
}
}
/// <summary>Logger instance</summary>
/// <param name="sFile">Full name of the file to use as logs. Ex : "MyLogs.txt"</param>
public Logger(string sFile)
{
dDir = new DirectoryInfo(Path.Combine(MyProject.AppPath, "logs"));
if (!dDir.Exists)
{
dDir.Create();
}
fFile = new FileInfo(Path.Combine(dDir.FullName,sFile));
if (!fFile.Exists)
{
using (StreamWriter sw = fFile.CreateText())
{
sw.WriteLine("{0:u}|Logger Started", DateTime.Now);
}
}
else
{
Add("Logger Started");
}
}
}
}
显然,我对这段代码的问题是,有时在该记录器的新实例有时间创建文件之前调用 Logger.Add。所以我的程序崩溃说“找不到文件”,但是,文件最终被创建,如果我使用相同的日志文件名重新启动我的程序,一切正常(因为文件现在存在......)
除了确保在创建文件之前不调用 logger.add 之外,有没有办法“锁定”类?
我试过lock方法,但是没用……Lock(this)没有做任何事情,我不能在方法本身上使用它。
【问题讨论】:
-
你能试试
if file.exists,如果不存在,运行system.threadding.threadding.sleep(10)再试一次。这有点小技巧,但它基本上会让你的应用程序在执行 add 方法之前“等待”。 -
@rockinthesixstring - 这将起作用,因为代码仍需要在第二个线程调用该方法之前创建文件。如果两个线程都休眠 10 毫秒,它们仍然可能发生冲突。
-
这完全超出了左侧字段,但可能值得查看 Log4Net 以了解如何进行日志记录。使用现有的轮子,而不是重新发明它们;-)。当然,这是假设您还没有尝试过。如果该假设不正确,请忽略此评论并接受我的道歉。
-
我没有看过log4net,我不想重新发明轮子,但是由于我还在学习c#,所以我想做我认为“简单”的东西我自己……虽然这可能确实比我想象的要复杂。
-
您能否发布足够的代码来重现该问题?或者至少是异常的堆栈跟踪?目前还不清楚是什么导致了问题。