希望得到一个快速回答(这似乎很好)...
我刚刚在我的应用程序上使用VS2010进行了性能分析,事实证明我花了大约20%的时间在Control.set_Text(string)函数中,因为我在我的应用程序的很多地方更新了标签.
该窗口有一个计时器对象(Forms计时器,而不是Threading计时器),它有一个timer1_Tick回调,每次滴答都会更新一个标签(以提供一种停止观察效果),每秒更新一次约15个标签.
有没有人有关于如何减少更新表单上文本所花费的时间的快速建议,而不是增加更新间隔?我应该使用其他结构或功能吗?
我自己遇到了这个问题,最后创建了我自己的简单Label控件.
.Net的Label控件是一个令人惊讶的复杂的野兽,因此比我们想要的慢.
您可以创建一个继承的类,在构造函数中Control调用SetStyle以使其进行双缓冲和用户绘制,然后覆盖OnPaint调用e.Graphics.DrawString和绘制Text属性的方法.
最后,覆盖Text或TextChanged调用Invalidate.
只要您不需要AutoSize,这将比标准Label控件快得多.
这是我的实施:(目前在生产中使用)
///<summary>A simple but extremely fast control.</summary>
///<remarks>Believe it or not, a regular label isn't fast enough, even double-buffered.</remarks>
class FastLabel : Control {
public FastLabel() {
SetStyle(ControlStyles.AllPaintingInWmPaint
| ControlStyles.CacheText
| ControlStyles.OptimizedDoubleBuffer
| ControlStyles.ResizeRedraw
| ControlStyles.UserPaint, true);
}
protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); Invalidate(); }
protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); Invalidate(); }
static readonly StringFormat format = new StringFormat {
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
protected override void OnPaint(PaintEventArgs e) {
e.Graphics.DrawString(Text, Font, SystemBrushes.ControlText, ClientRectangle, format);
}
}
Run Code Online (Sandbox Code Playgroud)
如果你不想中心,你可以摆脱或改变StringFormat.