【发布时间】:2015-10-10 22:39:56
【问题描述】:
在我的窗口应用程序中,有许多带有网格的屏幕。
我使用 DataTable 作为网格的 DataSource,DataTable 有一些非常大的数据集 (> 50,000),如果我们在加载 UI 时一次加载所有数据,则需要很长时间才能在屏幕上加载数据。响应直到所有数据都没有被加载,
所以我已经使用Background Worker在该网格中实现了增量加载。
这是代码:
// DoWork Event of the background Wroker.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
while (bgstop)
{
e.Result = addNewRecord();
if (Convert.ToBoolean(e.Result) == false)
{
e.Cancel = true;
bgstop = false;
killBGWorker();
break;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
// to add/merge the records in the DataTable
private bool addNewRecord()
{
int flag = 0;
try
{
Thread.Sleep(500); //optional
DataTable tableAdd = getTableData();
if (tableAdd.Rows.Count > 0)
{
dtRecords.Merge(tableAdd); // dtRecords is the DataTable which attached to grid
flag++;
}
else
backgroundWorker1.WorkerSupportsCancellation = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if (flag > 0)
return true;
else
return false;
}
// To get the next slot of Records from the DataBase
private DataTable getTableData()
{
DataTable dt = new DataTable();
start = nextRows * noOfRows;
stop = start + noOfRows;
dt = SQLHelper.getAllRecords(totalRows,noOfRows, start + 1, stop);
nextRows++;
return dt;
}
// kill the backgroudworker after the all data/records get loaded from database to grid/DataTable
private void killBGWorker()
{
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.CancelAsync();
}
上面的代码获取第一个定义的记录数(比如 200 条),然后在后台工作人员启动并开始在插槽中获取数据并将其与网格 DataSource 合并,直到所有数据(比如 >50,000 条记录)都加载到网格。
但是 UI 交互仍然存在一些问题,直到数据库中的所有记录都加载到网格中,UI 才会多次挂起 2-3 秒。
我经历了this,但在该示例中使用了 DataModel,但在我的情况下,他们只是从 DataBase 中的 DataTable 中获取了没有 DataModel,现在我们无法移动到 DataModel。
还有其他方法吗以良好的 UI 交互来实现增量加载?
或者
在当前场景中,有什么方法可以实现 IBindingList 吗?
【问题讨论】:
-
让 UI 保持响应式是否可以接受,或者增量检索行是否重要?是否允许用户与部分数据集进行交互?
-
为了获得良好的用户体验,我需要逐步检索行。是的,用户可以与部分数据集进行交互。
-
用户是否同时查看了所有网格?
-
@NamBình:可能!我正在使用 MDI 表单,其中存在多个屏幕/表单,用户可以打开多个表单。
标签: c# winforms datagridview datatable lazy-loading