我正在开发一个应用程序,需要显示来自外部系统的数据。这些数据可能会非常快速地到达,而每行所占的字节数相对较小。这意味着每个时间单位需要添加很多行。目前我似乎接收数据的速度比我处理数据的速度还要快,这意味着我的内存使用量正在上升。
我认为其中很大一部分原因是绘制实际的dataGridView。我已经对dataGridView进行了一些微调,希望能提高性能(例如禁用自动大小调整、特殊样式等)。
最近我添加了对行的颜色标记,这是必需的。目前我的应用程序的工作方式如下:
1. 我从外部系统接收数据 2. 我通过一个线程将数据放入队列(ConcurrencyQueue) 3. 另一个线程从该队列获取数据,处理并将其添加到绑定到表格的BindingList中。
实际的添加过程发生在一个具有两个参数的函数中: 1. 包含列项的列表(items) 2. 行颜色。(color)
它看起来像这样(半伪代码):
有哪些相对简单的方法可以提高性能?我考虑在处理忙碌时可能禁用datagrid的绘制,等到处理完成后再绘制(尽管不是首选)。另一件事可能是不那么频繁地更新,而不是每接收一个项目后都要更新(当添加新项目时,BindingList似乎会自动更新DataGridView)。希望有人愿意/能够帮助。
-编辑-
当以上述方式处理数据时,表单的响应性也变得非常糟糕,特别是经过一段时间后。(即使以上过程在backgroundworker(s)和background threads中进行)
我认为其中很大一部分原因是绘制实际的dataGridView。我已经对dataGridView进行了一些微调,希望能提高性能(例如禁用自动大小调整、特殊样式等)。
最近我添加了对行的颜色标记,这是必需的。目前我的应用程序的工作方式如下:
1. 我从外部系统接收数据 2. 我通过一个线程将数据放入队列(ConcurrencyQueue) 3. 另一个线程从该队列获取数据,处理并将其添加到绑定到表格的BindingList中。
实际的添加过程发生在一个具有两个参数的函数中: 1. 包含列项的列表(items) 2. 行颜色。(color)
它看起来像这样(半伪代码):
/* Store the color for the row in the color list so it is accessible from the event */
rowColors.Add(rowColor); //Class variable that stored the colors of the rows used in the DataGridCellFormatting event
/* Create the row that is to be added. */
ResultRow resultRow = new ResultRow();
foreach(item in items)
{
resultRow.Set(item); /* It's actually a dictionary because some fields are optional, hence this instead of a direct constructor call) */
}
bindingList.Add(resultRow);
/* Row coloring based on error is done in the OnCellFormatting() */
/* Auto scroll down */
if (dataGrid.Rows.Count > 0)
{
dataGrid.FirstDisplayedScrollingRowIndex = dataGrid.Rows.Count - 1;
}
如上面的代码所示,我收到的颜色被添加到一个List中,在datagridview的事件中使用,如下所示:
void DataGridCellFormattingEvent(object sender, DataGridViewCellFormattingEventArgs e)
{
// done by column so it happens once per row
if (e.ColumnIndex == dataGrid.Columns["Errors"].Index)
{
dataGrid.Rows[e.RowIndex].DefaultCellStyle.BackColor = rowColors[e.RowIndex];
}
}
BindingList被定义为:
BindingList bindingList;
其中ResultRow是一个类,其结构如下:
public class ResultRow
{
private int first = 0;
private string second = "";
private UInt64 third = 0;
private IPAddress fourth = null;
//etc
public ResultRow()
{
}
public void Set (<the values>) //In actuallity a KeyValuePair
{
//field gets set here
}
public UInt64 Third
{
get { return third; }
set { third = value; }
}
/* etc. */
有哪些相对简单的方法可以提高性能?我考虑在处理忙碌时可能禁用datagrid的绘制,等到处理完成后再绘制(尽管不是首选)。另一件事可能是不那么频繁地更新,而不是每接收一个项目后都要更新(当添加新项目时,BindingList似乎会自动更新DataGridView)。希望有人愿意/能够帮助。
-编辑-
当以上述方式处理数据时,表单的响应性也变得非常糟糕,特别是经过一段时间后。(即使以上过程在backgroundworker(s)和background threads中进行)