在主线程忙时连续更新UI [英] Updating UI continuously while the main thread is busy

查看:60
本文介绍了在主线程忙时连续更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在MainForm进行一些数据库相关工作时显示带有进度栏的新表单.我读到您不想将UI传递给新线程,所以我想知道解决此问题的最佳解决方案是什么?

I want to show a new Form with a Progressbar while my MainForm is doing some database related work. I've read that you don't want to pass the UI to a new thread, so I'm wondering what the best solution is to get around this problem?

我无法在另一个线程上执行与数据库相关的工作,因为它使用了十二个对UI和MainForm的调用.我也不能使用Application.DoEvents(),因为MainForm的线程正在类中工作,而且据我所知,您不应对类的父类进行任何调用.

I can't do the database related work on another thread since it uses a dozen calls to the UI and to the MainForm. I also can't use Application.DoEvents() since the MainForm's thread is working inside a class, and as far as I know you shouldn't do any calls to the parent of the class.

任何建议将不胜感激!

修改

为了澄清我实际上想知道的事情:

To clarify what I was actually wondering:

我的程序看起来像这样:

My Program looks kinda like this:

... Content = DatabaseClass.LoadContent();
ApplyContentToUI(Content);

我想做的是以下事情:

//Show a form here with a progressbar
... Content = DatabaseClass.LoadContent();
ApplyContentToUI(Content);
//Close the form here

但是自从执行ApplyContentToUI以来,它是aprox. 1秒后,我决定执行以下操作:

But since the time to execute ApplyContentToUI was aprox. 1 second I descided to do the following:

//Show a form here with a progressbar
... Content = DatabaseClass.LoadContent();
//Close the form here
ApplyContentToUI(Content);

如果与我不同,如果您需要在重新加载UI时显示进度栏,我建议您查看下面的评论和答案.

If you, unlike me, need to show the Progressbar while reloading the UI I suggest that you look at the comments and answers below.

推荐答案

@Servy建议不要将UI和逻辑混合,而应先进行逻辑处理,然后将结果应用于UI.尽管这不能满足最初的目的,但这似乎是解决我的问题的最简单方法. (带有进度栏的窗体只有在执行逻辑时才可见,但是现在在更新UI时才可见.)UI更新将以aprox完成.一秒钟,所以由于时间短,最后不一定真正需要进度条.

@Servy suggested that instead of mixing UI and logic, I would instead do the logic first and then apply the result to the UI. Although this does not fulfills the original purpose it seems to be the easiest way around my problem. (The Form with a Progressbar will only be visible while doing the logic, but now while updating the UI.) The UI-update will be done in aprox. a second so the Progressbar is not really necessary in the end, due to the short period of time.

对于那些在加载UI时仍需要进度栏的用户,在此问题下给出了一些不错的答案/解决方案.

For those who still require a Progressbar while loading the UI, some good answers/solutions were given under this question.

这篇关于在主线程忙时连续更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆