【发布时间】:2011-10-28 07:20:38
【问题描述】:
如何制作只存储最后 100 个条目的高效内存日志,并且可以快速将结果字符串输出到 TextBox(每次更新时)?
我正在使用File.AppendAllText 对文本文件进行实际记录,但希望能够查看我的应用程序中的最后一个条目。
【问题讨论】:
标签: c# .net wpf string logging
如何制作只存储最后 100 个条目的高效内存日志,并且可以快速将结果字符串输出到 TextBox(每次更新时)?
我正在使用File.AppendAllText 对文本文件进行实际记录,但希望能够查看我的应用程序中的最后一个条目。
【问题讨论】:
标签: c# .net wpf string logging
你看过Log4Net吗?
更具体地说是 log4net.Appender.MemoryAppender
【讨论】:
一个简单的队列有什么问题:
Queue<string> _items = new Queue<string>();
public void WriteLog(string value)
{
_items.Enqueue(value);
if(_items.Count > 100)
_items.Dequeue();
}
【讨论】:
创建一个长度为 maxloglines * maxlogentrywidth 的 char 数组。将其初始化为除每 maxlogentrywidth 个字符换行之外的所有空白。在您的日志记录方法中,您偏移到 maxlogentrywidth * rowIndex 并复制字符串中的 N 个字符,然后复制 maxlogentrywidth-N 个空格。将 rowIndex 增加 (rowIndex+1) % maxlines。
要输出到单个字符串以用于窗口,请使用 constructor that let's you index into an array 连接两个字符串:new string(chararry, curpos, len) + new string(chararray, 0, curpos-1, chararray.Lengs - curpos) 其中 curpos 是 maxlogentrywidth * rowIndex。
当然,您必须添加适当的错误检查和线程安全。
【讨论】:
可能的方法:
ObservableCollection<string>ItemsControl 和 ItemsTemplate 是无边界只读 TextBox
当然,这有其局限性,因为您无法选择跨项目,但其中没有字符串连接,并且使用正确类型的ItemsControl,您可以在需要时使用虚拟化。
【讨论】: