在C#Windows应用中显示等待消息 [英] Show wait message in c# windows app
问题描述
我正在做一个C#Windows应用程序.我必须做一些冗长的工作,就像许多表数据一个接一个地更新一样,所以我只想显示哪个数据库正在更新.在这里,我提供了一个示例程序来解决我的问题.
I am doing a c# windows application. I have to do some lengthy work just like many tables data update one by one so i just want to show which database updation is going on. Here i gave a sample program to solve my problem.
for (int i = 0; i < 10; i++)
{
richTextBox1.Text += "Now" + i + " is running \n";
System.Threading.Thread.Sleep(1000);
}
推荐答案
我认为您想要使用的是BackgroundWorker:
I think what you want is to use the BackgroundWorker:
var bw = new BackgroundWorker();
bw.DoWork += (sender1, eventArgs1) =>
{
var bw1 = (BackgroundWorker)sender1;
System.Threading.Thread.Sleep(1000);
bw1.ReportProgress(1);
};
bw.ProgressChanged += (sender2, eventArgs2) =>
{
richTextBox1.Text += "Now" + i + " is running \n";
};
bw.RunWorkerAsync()
我会在WPF中将一个Task与Dispatcher一起使用,但以上将与WinForms一起使用.
忘记了背景工作者的开始
I would use a Task with the Dispatcher in WPF, but the above will work with WinForms.
Forgot the start of the Background worker
我不太确定您要问的是什么,但我想您可能想要这样的东西:
I''m not really sure what you are asking, but I think you might want something like this:
int currentIndex = 0;
String[] updates; // the array containing all the updates you are doing
// as Strings since you didn't specify
doUpdates(); // call this when you want to get started
void doUpdates()
{
// check that current index is in bounds first, then...
using(BackgroundWorker bw = new BackgroundWorker)
{
richTextBox1.Text += "Now " + i + " is running\n";
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_Completed);
bw.RunWorkerAsync();
}
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
// do your updates on updates[currentIndex]
}
void queryWorker_Completed(object sender, RunWorkerCompletedEventArgs e)
{
++currentIndex;
doUpdates();
}
这将在BackgroundWorker线程上进行每次更新,然后更新到下一个索引并运行其余更新.
This will do each update on a BackgroundWorker thread, then update to the next index and run through the rest of the updates.
使用 ^ ],它对于用户体验来说要好得多.
Use a progress bar[^], it''s much better for the user experience.
这篇关于在C#Windows应用中显示等待消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!