简体   繁体   中英

How can I load multiple images using LoadAsync() in C#?

I'm trying to update the GUI, and I have an asynchronous function that uses LoadAsyc(), when I load just one image, it works but when I try to load more than one, the second one doesn't display.

This my code:

public UserFriendlyInterface()
{
    InitializeComponent();

    locationFileH5 = "";
    serverStatus = false;
    ipAddress = getLocalIPAddress();
    port = 5000;
    watcher = new FileSystemWatcher(@"flask_server\cnn\_prepImages_");
    watcher.EnableRaisingEvents = true;
    watcher.Changed += watcher_Changed;
}

private void watcher_Changed(object sender, FileSystemEventArgs e)
{
    updateImages();
}

async Task updateImages()
{
    pictureBoxNormalImg.WaitOnLoad = false;
    pictureBoxNormalImg.LoadAsync(@"flask_server\cnn\_prepImages_\normal.jpg");

    pictureBoxSegmentation.WaitOnLoad = false;
    pictureBoxSegmentation.LoadAsync(@"flask_server\cnn\_prepImages_\segmentation.jpg");
}

What you are trying to achieve can be achieved more robustly by querying the Name property of the FileSystemEventArgs object, and updating only the corresponding PictureBox .

private static void Watcher_Changed(object sender, FileSystemEventArgs e)
{
    PictureBox pictureBox;
    switch (e.Name.ToLowerInvariant())
    {
        case "normal.jpg": pictureBox = pictureBoxNormalImg; break;
        case "segmentation.jpg": pictureBox = pictureBoxSegmentation; break;
        default: pictureBox = null; break;
    }
    if (pictureBox != null)
    {
        Image image = null;
        try
        {
            using (var temp = new Bitmap(e.FullPath))
            {
                image = new Bitmap(temp);
            }
        }
        catch { } // Swallow exception
        if (image != null)
        {
            pictureBox.Invoke((MethodInvoker)(delegate ()
            {
                pictureBox.Image = image;
            }));
        }
    }
}

I would avoid the LoadAsync method because it is intended mainly for loading images from the internet, and because I don't totally trust it .


Update: There were two problems with my initial code:
1) Free file locked by new Bitmap(filePath)
2) FileSystemWatcher Changed event is raised twice

The updated code solves these problems (hopefully), but not in the most robust or efficient way possible.


Update: To make the code more efficient, by avoiding the repeated loading of the images caused by multiple firings of the Changed event, you could use the extension method OnChanged found in this answer . It suffices to replace the line below:

watcher.Changed += Watcher_Changed;

...with this one:

watcher.OnChanged(Watcher_Changed, 100);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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