How do you pass a BitmapImage from a background thread to the UI thread in WPF?

后端 未结 3 1854
-上瘾入骨i
-上瘾入骨i 2020-12-03 06:52

I have a background thread that generates a series of BitmapImage objects. Each time the background thread finishes generating a bitmap, I would like to show th

3条回答
  •  佛祖请我去吃肉
    2020-12-03 07:29

    The following uses the dispatcher to execute an Action delegate on the UI thread. This uses a synchronous model, the alternate Dispatcher.BeginInvoke will execute the delegate asynchronously.

    var backgroundThreadImage = GenerateImage(coordinate);
    
    GeneratedImage.Dispatcher.Invoke(
            DispatcherPriority.Normal,
            new Action(() =>
                {
                    GeneratedImage = backgroundThreadImage;
                }));
    

    UPDATE As discussed in the comments, the above alone will not work as the BitmapImage is not being created on the UI thread. If you have no intention of modifying the image once you have created it you can freeze it using Freezable.Freeze and then assign to GeneratedImage in the dispatcher delegate (the BitmapImage becomes read-only and thus threadsafe as a result of the Freeze). The other option would be to load the image into a MemoryStream on the background thread and then create the BitmapImage on the UI thread in the dispatcher delegate with that stream and the StreamSource property of BitmapImage.

提交回复
热议问题