我有一个用C#编写的Win GUI应用程序,其中有一个TextBox
我要写入日志的组件。在某些时候,它变得太负载,整个应用程序开始步履蹒跚。我想建立一种有效的机制使其成为FIFO,这意味着-将其设置为固定大小并自动删除最旧的内容。
有什么.net / c#功能吗?否则,什么是正确的方法?
更新:我也遇到了其他类型的文本数据问题,而不仅是日志问题。因此,这ListBox
对我来说不是一个合适的解决方案。
要为文本创建循环缓冲区,我将使用StringBuilder
,其容量设置为大约要显示的数据量的两倍。
const int DisplaySize = 10000;
StringBuilder fifo = new StringBuilder(2 * DisplaySize);
string AppendToFifo( string s )
{
if (s.Length >= DisplaySize) {
// FACT: the display will only include data from s
// therefore, toss the entire buffer, and only keep the tail of s
fifo.Clear();
fifo.Append(s, s.Length - DisplaySize, DisplaySize);
return fifo.ToString();
}
if (fifo.Length + s.Length > fifo.Capacity) {
// FACT: we will overflow the fifo
// therefore, keep only data in the fifo that remains on the display
fifo.Remove(0, fifo.Length + s.Length - DisplaySize);
}
fifo.Append(s);
if (fifo.Length <= DisplaySize) {
// FACT: the entire fifo content fits on the display
// therefore, send it all
return fifo.ToString();
}
// FACT: the fifo content exceed the display size
// therefore, extract just the tail
return fifo.ToString(fifo.Length - DisplaySize, DisplaySize);
}
如果if条件都不为真,则快速路径将避免所有不必要的副本(在字符串不可变的.NET世界中,无法避免创建输出字符串的最终副本)。在其他情况下,仅复制所需的字符。增加缓冲区的容量将提高快速路径的利用率。我一直在避免做的是创建一个字符串对象,该对象具有保留在显示器上的旧内容,除了连接新内容外,它没有其他用途,并立即变成垃圾。
显然,如果使用p / invoke传递指向StringBuffer内容的指针,而不是复制出子字符串,则效率会更高。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句