BackgroundWorker 和 Progressbar.Show()
我正在使用 Visual Studio 2010 和 C#,并尝试显示进度条,但它不起作用。
我听一个事件。如果发生这种情况,我想做一些工作并在执行此操作时显示进度条。
这就是我所做的:
static void Main(string[] args) {
ProgressForm form = new ProgressForm();
new FileWatcher(form).Start();
Application.Run();
}
ProgressForm:
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
private void bgWorker_DoWork(object sender, DoWorkEventArgs e) {
this.Show();
....
}
但没有任何显示。为什么这不起作用?
谢谢 再见尤尔根
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不应更改 UI 表单后台线程。这应该只能从主线程完成。您可以在启动后台工作程序之前显示基本进度条,并将其隐藏在后台工作程序 RunWorkerCompleted 事件处理程序中。要报告真正的进展,您需要按照 Giorgi 的建议进行实施。
You should not change the UI form background threads. This should be done only from the main thread. You can show a basic progress bar just before you start the background worker and hide it in the background worker RunWorkerCompleted event handler. To report real progress you need an implementation as Giorgi suggested.
您无法使用 BGW 来显示表单,线程没有正确的状态。您必须使用 Thread,以便可以调用其 SetApartmentState() 方法将其切换到 STA。您还需要线程上的消息循环来保持表单处于活动状态,这需要调用 Application.Run()。并且表单必须在该线程上创建。因此:
这种窗体的一个大问题是它不能被 UI 线程上的任何窗口所拥有。让它有消失在另一个应用程序窗口后面的趋势。此外,您的 UI 线程仍然处于死状态,几秒钟后,其窗口将在标题栏中显示“未响应”消息。
正确的方法是相反:在另一个线程上运行耗时的代码,BGW 将是一个非常好的选择。 UI 线程应该显示您的进度表。 BackgroundWorker.ReportProgress 非常适合保持进度条更新。
You cannot use a BGW to display a form, the thread does not have the proper state. You'll have to use a Thread so you can call its SetApartmentState() method to switch it to STA. You also need a message loop on the thread to keep the form alive, that requires a call to Application.Run(). And the form must be created on that thread. Thus:
One big issue with this form is that it cannot be owned by any window on your UI thread. Giving it the tendency to disappear behind the window of another application. Also, your UI thread is still dead, its windows will ghost with the "Not Responding" message in their caption bar after a few seconds.
The proper way to do this is the other way around: run the time-consuming code on another thread, a BGW would be a very good choice. The UI thread should display your progress form. BackgroundWorker.ReportProgress is ideal to keep the progress bar updated.
为了从BackgroundWorker报告进度,您需要从
DoWork
事件处理程序调用ReportProgress
方法,并在BackgroundWorker.ProgressChanged 事件In order to report progress from the BackgroundWorker you need to call
ReportProgress
method from theDoWork
event handler and show the progress in handler of BackgroundWorker.ProgressChanged Event