How do I load images in the background?

前端 未结 5 1209
小鲜肉
小鲜肉 2021-01-03 09:50

I am trying to load an image in the background and then update the UI. I have been playing with this all day and I don\'t know what I am missing. I keep getting the follow

5条回答
  •  隐瞒了意图╮
    2021-01-03 10:18

    What I tend to use the ThreadPool.QueueUserWorkItem to load the image, then when the operation completes I call back to the UI thread using the thread-safe Dispatcher object. The image source is not thread safe, you will have to use something like the JpegBitmapDecoder, there is also a PngBitmapDecoder.

    For Example:

    public Window()
    {
        InitializeComponent();
    
        ThreadPool.QueueUserWorkItem(LoadImage,
             "http://z.about.com/d/animatedtv/1/0/1/m/simp2006_HomerArmsCrossed_f.jpg");
    }
    
    public void LoadImage(object uri)
    {
        var decoder = new JpegBitmapDecoder(new Uri(uri.ToString()), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
        decoder.Frames[0].Freeze();
        this.Dispatcher.Invoke(DispatcherPriority.Send, new Action(SetImage), decoder.Frames[0]);
    }
    
    public void SetImage(ImageSource source)
    {
        this.BackgroundImage.Source = source;
    }
    

提交回复
热议问题