Click here to Skip to main content
14,425,324 members

C# async/await not working with mysql

dragnscalearmor asked:

Open original thread
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()

        private void Button1_Click(object sender, EventArgs e)
            timer1.Enabled = true;

        private async void GetData()
            string sql = "SELECT * FROM websites";
            MySqlConnection con1 = new MySqlConnection(strconnect);
                MySqlCommand cmd = new MySqlCommand(sql, con1);
                MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync();
                while (reader.Read())

        private void Timer1_Tick(object sender, EventArgs e)
            if (c > 20)
                c = 0;
            int num = r.Next(1, 999999);

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.
Tags: C#


When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100