skip to Main Content

I have mysql loop

using (var conn = new MySqlConnection(connectionString))
{
    try
    {
        conn.Open();
        int count = 1;

        foreach (var value in values)
        {
            MySqlCommand cmd;
            string qu = "INSERT INTO db(val1,val2,val3,val4,val5) VALUES("+value+")";
            cmd = new MySqlCommand(qu, conn);
            cmd.ExecuteNonQuery();
            textBox1.Text = count.ToString();
            count++;
        }

        conn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: " + ex.ToString());
    }
}

My goal is to show in textBox1 counter (loop has 18k+ rows), but when I start foreach loop my window is frozen and shows nothing until loop is end, and then show numbers in textbox, but I want to show current count number in real time.

2

Answers


  1. In .NET you have couple of options, which i briefly will list below:

    • creating and managing threads directly with Thread class and its API, which is "old-fashioned" way

    • using async/await to enable asynchronous code (your libraries need to support async operations)

    • if your libraries are not supporting async operations, you can always try wrapping it with Task.Run

    You can find dozens of resources on each topic on the internet, so i am not going to go deeply into details.

    In your case i guess there should be method ExecuteNonQueryAsync

    And regarding UI – there is always good idea to show user sort of progress indication when we have operation that user waits for.

    Login or Signup to reply.
  2. You need one more thread to perform this action.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search