Search code examples
c#winformspicturebox

How to load an image in C# Winforms from an URL without application freezing?


I have some PictureBox objects in foreach. It loops all the PictureBoxes and loads images from the internet for them. Each PictureBox has a different picture downloading. It works good, but the problem is the application freezes until all the images load. Is there a way to make them appear one by one and not all at the same time?

Code:

index++;                
lpb[index].Load(url); 
//lpb is a list of PictureBoxes (List<PictureBox>)

Thanks!


Solution

  • Use LoadAsync instead of Load. As the docs explain you should also set the WaitOnLoad property to false.

    The LoadProgressChanged and LoadCompleted events can be used to track progress.

    From the doc example:

    private void startButton_Click(object sender, EventArgs e)
    {
        // Ensure WaitOnLoad is false.
        pictureBox1.WaitOnLoad = false;
    
        // Load the image asynchronously.
        pictureBox1.LoadAsync(@"http://localhost/print.gif");
    }