问题描述
我正试图让我的大脑围绕这个异步/等待的事情,并认为我会尝试使用一个小的数据库应用程序。下面是代码,它工作正常,但GetData()方法不是异步运行,因为UI在连接/拉动数据时仍然冻结。我有随机数填充listBox2作为UI冻结的视觉提示。数据库只是我为测试此代码而制作的网站地址列表。
I'm trying to get my brain around this async / await thing, and thought I'd try it with a little database app. Below is the code, which works fine, but the GetData() method is not running asynchronously because the UI still freezes when it's connecting/pulling the data. I have the random numbers filling listBox2 as a visual cue that the UI is freezing. The database is just a list of website addresses I made to test this code.
using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace MySQLasync
{
public partial class Form1 : Form
{
// public variables and constants
string strconnect = "Server = localhost; Port=3306; Database=mydbase; Uid=myusername; Pwd=mypasswd;";
Random r = new Random();
int c = 0;
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
GetData();
}
private async void GetData()
{
listBox1.Items.Clear();
string sql = "SELECT * FROM websites";
MySqlConnection con1 = new MySqlConnection(strconnect);
{
con1.Open();
MySqlCommand cmd = new MySqlCommand(sql, con1);
MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync();
while (reader.Read())
{
listBox1.Items.Add(reader["title"].ToString());
}
con1.Close();
}
}
private void Timer1_Tick(object sender, EventArgs e)
{
c++;
if (c > 20)
{
c = 0;
listBox2.Items.Clear();
}
int num = r.Next(1, 999999);
listBox2.Items.Add(num);
}
}
}
我尝试了什么:
无论我是否使用async / await,代码运行完全相同。也就是说,UI仍然冻结了与访问数据并添加到listBox1相同的时间。
有人可以解释我在这里做错了什么?我希望UI在访问和加载数据时保持响应。不确定我是否有async / await的整个概念。谢谢。
What I have tried:
Whether I use async / await or not, the code runs exactly the same. That is, the UI still freezes for the same amount of time as the data is accessed and added to listBox1.
Can someone please explain what I'm doing wrong here? I want the UI to remain responsive while the data is accessed and loaded. Not sure I have the whole concept of async/await yet. Thank you.
推荐答案
这篇关于C#async / await无法使用mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!