简体   繁体   English

如何在后台线程中加载图像而不影响UI?

[英]How to load images in background thread without affecting the UI?

I am fetching a number of images from the internet and loading into my winform. 我正在从互联网上获取大量图像并加载到我的winform中。 Everything works fine except for the time lag when the images are fetched from a slow connection. 除了从慢速连接中提取图像的时间延迟外,一切正常。 I want the images to be fetched in background but the UI should not become unresponsive. 我希望在后台获取图像,但UI不应该没有响应。

I tried 'BackgroundWorker' but it didn't work. 我试过'BackgroundWorker',但它没有用。 Is there any other way of doing this? 有没有其他方法这样做? I read about async calls but I am not sure if it will work for me. 我读到了异步调用,但我不确定它是否适用于我。

Background Worker :: 背景工人::

 foreach(String str in images )
            {
              BackgroundWorker bw=new BackgroundWorker();
              bw.DoWork += (s, e) => { run(str); };  // 
              bw.RunWorkerAsync();
            }

and run() simply sets the image url to the picture box. run()只是将图像URL设置为图片框。

You can't make UI updates except from the thread you created the UI object on. 除了从创建UI对象的线程外,您无法进行UI更新。

You can however use "Invoke" to make a call on the class's main thread. 但是,您可以使用“Invoke”在类的主线程上进行调用。

Invoke( (Action)(() => { pictureBox.image = loadedImage; }) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM