在预期脚本之前执行映像下载

本文关键字:执行 映像 下载 脚本 | 更新日期: 2023-09-27 18:32:46

我今天遇到了这个"有趣"的问题。我在 wpf 窗口上有一个按钮,当我按下它时,我希望一个矩形变得可见并扩展到我的主窗口的大小。然后,文本保持在矩形内以在其中心对齐。发生这种情况后,我希望脚本从 Web 下载图像以开始执行。然而。。。当我按下按钮时,我的矩形不可见,而是 exe 开始下载图像......我认为代码应该按顺序执行...

On button_1 press(blah blah){
expander1.IsExpanded = false; //just an expander i use to hide a few elements
            pleasewait.Visibility = Visibility.Visible; //pleasewait - rectangle
            plswait_label.Visibility = Visibility.Visible; // plswait_lable - label
            pleasewait.Height = window_main.Height;
            pleasewait.Width = window_main.Width;
            plswait_label.HorizontalAlignment = HorizontalAlignment.Center;
            plswait_label.VerticalAlignment = VerticalAlignment.Center;
            image1.Source = null; // dumping previous image before downloading a new one

//This is the script to download the image and do some other stuff..
    string path = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
    Uri urlUri = new Uri(address.Text);
    var request = WebRequest.CreateDefault(urlUri);
    byte[] buffer = new byte[4096];
    using (var target = new FileStream(path + @"'Temp'br_temp.png", FileMode.Create, FileAccess.Write))
    {
        using (var response = request.GetResponse())
        {
            using (var stream = response.GetResponseStream())
            {
                int read;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    target.Write(buffer, 0, read);
                }
            }
        }
    }

    Bitmap resizedImage;
    System.Drawing.Size newSize = new System.Drawing.Size(266, 150);
    using (System.Drawing.Image originalImage = System.Drawing.Image.FromFile(path + @"'Temp'br_temp.png"))
        resizedImage = new System.Drawing.Bitmap(originalImage, newSize);
    resizedImage.Save(path + @"'Temp'temp.png", System.Drawing.Imaging.ImageFormat.Jpeg);
    resizedImage.Dispose();
    BitmapImage MainImage = new BitmapImage();
    MainImage.BeginInit();
    MainImage.UriSource = new Uri(path + @"'Temp'temp.png");
    MainImage.DecodePixelWidth = 266;
    MainImage.DecodePixelHeight = 150;
    MainImage.EndInit();
    image1.Source = MainImage;
}

有趣的是,如果我删除下载代码,矩形实际上可以执行我想要的操作。

在预期脚本之前执行映像下载

下载正在阻止 UI 线程。在下载完成之前,UI 上的任何内容都不起作用。

您需要将下载代码移出 UI 线程。

执行此操作的一种简单方法是使用后台工作者

与往常一样,我建议阅读乔·阿尔巴哈里的电子书