以Win形式异步从DB加载数据 [英] Loading data from DB asynchronously in win forms
本文介绍了以Win形式异步从DB加载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
很多时候,我们使用表单加载中的DB数据填充UI,这就是为什么表单冻结了几秒钟的原因.所以我只想知道如何异步加载数据并在表单加载中填充UI,因此我的表单不会冻结并且也将响应,但是我不想使用后台工作程序类.请帮助我提供可以解决我的问题的示例代码.
many time we populate UI with data from DB in the form load and that is why form gets freeze for few second. so i just want to know how can i load data asynchronously and populate UI in form load as a result my form will not freeze and also will be responsive but i don't want to use background worker class. please help me with sample code which can solve my problem.
谢谢
推荐答案
下面是一个注释良好的示例代码:
Here is a well commented example code:
// This method can be called on Form_Load, Button_Click, etc.
private void LoadData()
{
// Start a thread to load data asynchronously.
Thread loadDataThread = new Thread(LoadDataAsync);
loadDataThread.Start();
}
// This method is called asynchronously
private void LoadDataAsync()
{
DataSet ds = new DataSet();
// ... get data from connection
// Since this method is executed from another thread than the main thread (AKA UI thread),
// Any logic that tried to manipulate UI from this thread, must go into BeginInvoke() call.
// By using BeginInvoke() we state that this code needs to be executed on UI thread.
// Check if this code is executed on some other thread than UI thread
if (InvokeRequired) // In this example, this will return `true`.
{
BeginInvoke(new Action(() =>
{
PopulateUI(ds);
}));
}
}
private void PopulateUI(DataSet ds)
{
// Populate UI Controls with data from DataSet ds.
}
这篇关于以Win形式异步从DB加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文