英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论