gpt4 book ai didi

c# - 从后台线程更新时 UI 稍微卡住

转载 作者:太空狗 更新时间:2023-10-30 01:23:53 26 4
gpt4 key购买 nike

我有一个带有 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 构造函数将转到硬盘驱动器并将图像加载到内存中。

InvokeBeginInvoke 将运行您提供的委托(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com