MySQL循环冻结窗口在C#中。

huangapple go评论66阅读模式
英文:

Mysql Loop freeze Window in C#

问题

我想要在textBox1中显示计数器(循环有18k+行),但当我启动foreach循环时,我的窗口会冻结,直到循环结束才会显示文本框中的数字,但我想实时显示当前的计数数字。

英文:

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.

答案1

得分: 0

在.NET中,您有几种选项,我将简要列出如下:

  • 使用Thread类及其API直接创建和管理线程,这是一种"老式"的方法

  • 使用async/await来启用异步代码(您的库需要支持异步操作)

  • 如果您的库不支持异步操作,您可以尝试使用Task.Run来包装它

您可以在互联网上找到关于每个主题的大量资源,所以我不打算深入讨论细节。

在您的情况下,我猜应该有一个名为ExecuteNonQueryAsync的方法

关于用户界面(UI) - 当用户需要等待的操作时,始终显示一种进度指示是一个不错的主意。

英文:

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.

答案2

得分: -3

你需要再添加一个线程来执行此操作。

英文:

You need one more thread to perform this action.

huangapple
  • 本文由 发表于 2023年4月17日 16:20:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76033057.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定