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

后端 未结 3 1853
-上瘾入骨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:42

    In the background thread work with Streams.

    For example, in the background thread:

    var artUri = new Uri("MyProject;component/../Images/artwork.placeholder.png", UriKind.Relative);
    
    StreamResourceInfo albumArtPlaceholder = Application.GetResourceStream(artUri);
    
    var _defaultArtPlaceholderStream = albumArtPlaceholder.Stream;
    
    SendStreamToDispatcher(_defaultArtPlaceholderStream);
    

    In the UI thread:

    void SendStreamToDispatcher(Stream imgStream)
    {
         dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
         {
            var imageToDisplay = new BitmapImage();
            imageToDisplay.SetSource(imgStream);
    
            //Use you bitmap image obtained from a background thread as you wish!
         })); 
    }
    

提交回复
热议问题