Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

c# - Loading data from DB asynchronously in win forms

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.

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a well commented example code:

Example:

// 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.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...