[英]WinForms UI : Using async / await and ADO.NET
I am trying to learn async
await
in WinForms
where on a button click I have 我正在尝试在
WinForms
中学习async
await
在其中单击按钮,我有
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
. 我正在用两种希望
asynchronously
调用的方法搜索FirstNames和LastNames 。 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". 单击按钮时,我的意图是
lblSearchStatus
的文本应从“正在搜索...” ---> “正在搜索名字” ---> “正在搜索姓氏” ---> “ 123名字/姓氏”找到名字”。 But when I run it the label changes directly from "Searching.." to "123 First/Last Names found". 但是,当我运行它时,标签直接从“正在搜索..”更改为 “找到的123个姓氏/名字”。
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. 这有点晚了,但可能会帮助其他人寻找答案:我还不能100%确定,但是好像UI线程被阻塞了,因此标签没有被刷新,如果我们使用“ Task.Run ”,它将使用另一个线程来运行资源密集型进程。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.