很多时候我们在表单加载中使用数据库中的数据填充 UI,这就是表单卡住几秒钟的原因。所以我只想知道如何异步加载数据并在表单加载中填充 UI,结果我的表单不会卡住并且也会响应,但我不想使用后台工作类。请帮助我提供可以解决我的问题的示例代码。
谢谢
最佳答案
这是一个注释良好的示例代码:
示例:
// 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.
}
关于c# - 在winforms中从数据库异步加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4479319/