简体   繁体   中英

WinForms UI : Using async / await and ADO.NET

I am trying to learn async await in WinForms where on a button click I have

private async void btnSearch_Click(object sender, EventArgs e)
{   
    lblSearchStatus.Text = "Searching...";

    await FetchFirstNames();
    lblSearchStatus.Text = "searching for First Name";
    await FetchLastNames();
    lblSearchStatus.Text = "searching for Last Name";   
}

I am searching for FirstNames and LastNames in two different methods which I wish to call asynchronously . Both methods are similar and code goes like this:

private async Task FetchFirstNames()
{
    ...
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);       
        SqlDataAdapter dap = new SqlDataAdapter(command);
        DataTable tblMatches = new DataTable();
        await Task.Run(() =>dap.Fill(tblMatches)); //it takes about 5s to complete.                 
        ...
        lblSearchStatus.Text = tblMatches.Rows.Count.ToString() + " first names found.";        
    }
}

On clicking the button my intention is that the text of lblSearchStatus should change from "Searching..." ---> "searching for First Name" ---> "searching for Last Name" ---> "123 First/Last names found". But when I run it the label changes directly from "Searching.." to "123 First/Last Names found".
Where I am going wrong?

This is kind of late, but may help anybody else looking for an answer: I am not 100% sure yet, but seems like the UI thread was getting blocked, hence the label was not getting refreshed, and if we use "Task.Run" it will use another thread to run the resource intensive process.

private async void button1_Click(object sender, EventArgs e)
{
    lblSearchStatus.Text = "searching for First Name--";

    Task task1 = Task.Run(() => FetchFirstNames());
    await task1;

    lblSearchStatus.Text = lblSearchStatus.Text + " searching for Last Name-";
    Task task2 = Task.Run(() => FetchLastNames());
    await task2;

    lblSearchStatus.Text = lblSearchStatus.Text + " ---- All Done ----";
}

private async Task FetchFirstNames()
{
    string str1 = "";

    lblSearchStatus.Text = lblSearchStatus.Text + " Start first name -";

    for (int i = 0; i < 100000000; i++)
    {
        str1 = i.ToString();
    }

    lblSearchStatus.Text = lblSearchStatus.Text + " first name: i=" + str1;
}

private async Task FetchLastNames()
{
    string str1 = "";

    lblSearchStatus.Text = lblSearchStatus.Text + " Start Last name -";

    for (int i = 0; i < 100000000; i++)
    {
        str1 = i.ToString();
    }

    lblSearchStatus.Text = lblSearchStatus.Text + " last name: i=" + str1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM