在win表单中异步加载来自DB的数据

Tho*_*mas 5 c#

很多时候我们使用表单加载中来自DB的数据填充UI,这就是为什么表单会冻结几秒钟.所以我只想知道如何异步加载数据并在表单加载中填充UI,因此我的表单不会冻结,也会响应,但我不想使用后台工作者类.请帮我提供可以解决我的问题的示例代码.

谢谢

dec*_*one 10

这是一个评论很好的示例代码:

例:

// 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.
}
Run Code Online (Sandbox Code Playgroud)