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

时间:2012-04-28 14:42:53

标签: c# wpf drawing execution shapes

我今天遇到了这个“有趣”的问题。 我在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;
}

有趣的是,如果我删除了下载代码,那么矩形实际上就是我想要的......

1 个答案:

答案 0 :(得分:1)

下载阻止了UI线程。在下载完成之前,UI上的任何内容都无效。

您需要从UI线程中移除下载代码。

一种简单的方法是使用BackgroundWorker

与往常一样,我建议您阅读Joe Albahari's ebook