- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个带有 4 个 PictureBox 控件的 Winform,每个控件将包含一个不同的图像。过程是:
事件 x 被引发,来自该事件的事件参数包含每个图像的文件名 (4),依此类推(文件存在等)。然后,我必须更新 UI。
我通常使用调用:
Invoke((ThreadStart)delegate()
{
picBig.Image = new Bitmap(strImageBig);
picLittle1.Image = new Bitmap(saLittle[0]);
picLittle2.Image = new Bitmap(saLittle[1]);
picLittle3.Image = new Bitmap(saLittle[2]);
});
// saLittle[] is a string array, contains, filenames: "image1.jpg"
但是当它执行时,表单卡住了一小段时间,大约 500 毫秒,我知道这是一个很小的间隔但它很明显,然后应用程序继续正常运行。
我试图找出“UI 卡住”的原因,然后,经过研究,我找到了 BeginInvoke。现在我的代码如下所示:
BeginInvoke((MethodInvoker)delegate
{
picBig.Image = new Bitmap(strImageBig);
picLittle1.Image = new Bitmap(saLittle[0]);
picLittle2.Image = new Bitmap(saLittle[1]);
picLittle3.Image = new Bitmap(saLittle[2]);
});
这样会快一点。但是 UI 仍然卡顿了 200~300ms。
在我读过的文章中,他们说 BeginInvoke 是比 Invoke 更好的方法。
代码运行正常,逻辑或其他任何方面都没有问题。我只想知道为什么会这样。我不想让这个疑问不清楚。该项目已经完成。希望这对其他人有用。
也许这不是正确的做法。我知道有很多方法可以从后台线程更新 UI,但是还有另一种方法可以更快进行更新吗?
或者,您认为图像加载是原因吗?有没有其他方法可以更快地加载图像?
提前致谢。
最佳答案
这是因为您实际上是在 UI 线程上从磁盘加载图像以及设置控件的内容。使用文件路径调用 Bitmap
构造函数将转到硬盘驱动器并将图像加载到内存中。
Invoke
和 BeginInvoke
将运行您提供的委托(delegate)在创建控件的线程上,这很可能会是 UI 线程。
...but is there another way to make an update faster?
在您的后台线程上加载图像,当它们实际加载时,调用图像并将其设置到控件中。
var big = new Bitmap(strImageBig);
var little1 = new Bitmap(saLittle[0]);
var little2 = new Bitmap(saLittle[1]);
var little3 = new Bitmap(saLittle[2]);
Invoke((ThreadStart)delegate()
{
picBig.Image = big;
picLittle1.Image = little1;
picLittle2.Image = little2;
picLittle3.Image = little3;
});
关于c# - 从后台线程更新时 UI 稍微卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10956629/
我有一个可视化 C# 项目,我想从中编译两个可执行文件:Full.exe 和 Limited.exe。 Limited.exe 只是隐藏了几个 UI 控件。 我正在考虑添加另一对解决方案配置(Debu
我和我的伙伴正计划将我们拥有的 python 应用程序移植到 iOS。我们使用 numpy 的 SVD、范数和 pinv功能,我不知道如何转换为 iOS。我查看了 Accelerate文档,没有看到任
即,它永远不会使用某些特定的 upperBound 参数连续生成超过 16 个偶数: Random random = new Random(); int c = 0; int max = 17; in
我的问题是我必须使用第三方函数/算法,它采用 double 数组作为输入,但显然对输入数据中的非常小的变化很敏感.但是对于我的应用程序,我必须为(几乎)相同的输入获得相同的结果!特别是我有两个测试输入
mouse_event 函数将光标发送到稍有错误的坐标(偏离 1-20 像素)。它“关闭”的程度取决于我不太清楚的模式。 这是我的代码 int x, y; int repeats = 1000; in
在 C++ 类(class)中,我学到了避免重复计算、使用更多加法而不是更多乘法、避免幂等技巧来提高性能。然而,当我尝试让他们用 Julia-Lang 优化代码时,我对相反的结果感到惊讶。 例如,这里
好的。请耐心听我说,我不擅长解释事情。 我有一个通过网站上的表格收集的联系信息数据库。显然,人们不小心(或故意,但修复是一个不同的问题)多次按下“提交”,因此该数据库中有很多重复的行。 因此,tabl
我一直在用各种语言和实现实现相同的代码(在 Blackjack 中发牌而不爆牌的方法的数量)。我注意到的一个奇怪之处是,Python 在 C 中调用分区函数的实现实际上比用 C 编写的整个程序快一点。
我在使用 Pandas 解析数据的时间戳时遇到问题。 我尝试解析的日期时间格式示例类似于 2012-05-02 01:00:00-05:00。从 Pandas 文档中,我被驱动到相关的 Python
下面函数模板的目标是取任意unordered_map并产生一个新的unordered_map与 key_type和 mapped_type倒。下面的函数适用于 std::unorderd_map .我
我是一名优秀的程序员,十分优秀!