<p>What's the best way to asynchronously load an BitmapImage in C# using WPF?  </p>

[{'answer_id': 36757, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 2, 'selected': False, 'text': '<p>Assuming you\'re using data binding, setting <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.binding.isasync.aspx" rel="nofollow noreferrer">Binding.IsAsync</a> property to True seems to be a standard way to achieve this.\nIf you\'re loading the bitmap in the code-behind file using background thread + Dispatcher object is a common way to update UI asynchronous</p>\n'}, {'answer_id': 40774, 'author': 'bentford', 'author_id': 946, 'author_profile': 'https://Stackoverflow.com/users/946', 'pm_score': 0, 'selected': False, 'text': '<p>Use or extend System.ComponentModel.BackgroundWorker:<br>\n<a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx</a></p>\n\n<p>Personally, I find this to be the easiest way to perform asynchronous operations in client apps.  (I\'ve used this in WinForms, but not WPF.  I\'m assuming this will work in WPF as well.)</p>\n\n<p>I usually extend Backgroundworker, but you dont\' have to.</p>\n\n<pre><code>public class ResizeFolderBackgroundWorker : BackgroundWorker\n{\n\n    public ResizeFolderBackgroundWorker(string sourceFolder, int resizeTo)\n    {\n        this.sourceFolder = sourceFolder;\n        this.destinationFolder = destinationFolder;\n        this.resizeTo = resizeTo;\n\n        this.WorkerReportsProgress = true;\n        this.DoWork += new DoWorkEventHandler(ResizeFolderBackgroundWorker_DoWork);\n    }\n\n    void ResizeFolderBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)\n    {\n        DirectoryInfo dirInfo = new DirectoryInfo(sourceFolder);\n        FileInfo[] files = dirInfo.GetFiles("*.jpg");\n\n\n        foreach (FileInfo fileInfo in files)\n        {\n            /* iterate over each file and resizing it */\n        }\n    }\n}\n</code></pre>\n\n<p>This is how you would use it in your form:</p>\n\n<pre><code>    //handle a button click to start lengthy operation\n    private void resizeImageButtonClick(object sender, EventArgs e)\n    {\n        string sourceFolder = getSourceFolderSomehow();\n        resizer = new ResizeFolderBackgroundWorker(sourceFolder,290);\n        resizer.ProgressChanged += new progressChangedEventHandler(genericProgressChanged);\n        resizer.RunWorkerCompleted += new RunWorkerCompletedEventHandler(genericRunWorkerCompleted);\n\n        progressBar1.Value = 0;\n        progressBar1.Visible = true;\n\n        resizer.RunWorkerAsync();\n    }\n\n    void genericRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n    {\n        progressBar1.Visible = false;\n        //signal to user that operation has completed\n    }\n\n    void genericProgressChanged(object sender, ProgressChangedEventArgs e)\n    {\n        progressBar1.Value = e.ProgressPercentage;\n        //I just update a progress bar\n    }\n</code></pre>\n'}, {'answer_id': 783633, 'author': 'kevindaub', 'author_id': 27669, 'author_profile': 'https://Stackoverflow.com/users/27669', 'pm_score': 2, 'selected': False, 'text': '<p>To elaborate onto aku\'s answer, here is a small example as to where to set the IsAsync:</p>\n\n<pre><code>ItemsSource="{Binding IsAsync=True,Source={StaticResource ACollection},Path=AnObjectInCollection}"\n</code></pre>\n\n<p>That\'s what you would do in XAML.</p>\n'}, {'answer_id': 2672929, 'author': 'Brian', 'author_id': 321017, 'author_profile': 'https://Stackoverflow.com/users/321017', 'pm_score': 3, 'selected': False, 'text': '<p>I was just looking into this and had to throw in my two cents, though a few years after the original post (just in case any one else comes looking for this same thing I was looking into). </p>\n\n<p>I have an <strong>Image</strong> control that needs to have it\'s image loaded in the background using a <strong>Stream</strong>, and then displayed. </p>\n\n<p>The problem that I kept running into is that the <strong>BitmapSource</strong>, it\'s <strong>Stream</strong> source and the <strong>Image</strong> control all had to be on the same thread.</p>\n\n<p>In this case, using a Binding and setting it\'s IsAsynch = true will throw a cross thread exception. </p>\n\n<p>A BackgroundWorker is great for WinForms, and you can use this in WPF, but I prefer to avoid using the WinForm assemblies in WPF (bloating of a project is not recommended, and it\'s a good rule of thumb too). This should throw an invalid cross reference exception in this case too, but I didn\'t test it.</p>\n\n<p>Turns out that one line of code will make any of these work:</p>\n\n<pre><code>//Create the image control\nImage img = new Image {HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Stretch};\n\n//Create a seperate thread to load the image\nThreadStart thread = delegate\n     {\n         //Load the image in a seperate thread\n         BitmapImage bmpImage = new BitmapImage();\n         MemoryStream ms = new MemoryStream();\n\n         //A custom class that reads the bytes of off the HD and shoves them into the MemoryStream. You could just replace the MemoryStream with something like this: FileStream fs = File.Open(@"C:\\ImageFileName.jpg", FileMode.Open);\n         MediaCoder.MediaDecoder.DecodeMediaWithStream(ImageItem, true, ms);\n\n         bmpImage.BeginInit();\n         bmpImage.StreamSource = ms;\n         bmpImage.EndInit();\n\n         //**THIS LINE locks the BitmapImage so that it can be transported across threads!! \n         bmpImage.Freeze();\n\n         //Call the UI thread using the Dispatcher to update the Image control\n         Dispatcher.BeginInvoke(new ThreadStart(delegate\n                 {\n                         img.Source = bmpImage;\n                         img.Unloaded += delegate \n                                 {\n                                         ms.Close();\n                                         ms.Dispose();\n                                 };\n\n                          grdImageContainer.Children.Add(img);\n                  }));\n\n     };\n\n//Start previously mentioned thread...\nnew Thread(thread).Start();\n</code></pre>\n'}, {'answer_id': 19470572, 'author': 'Cornel Marian', 'author_id': 736113, 'author_profile': 'https://Stackoverflow.com/users/736113', 'pm_score': 2, 'selected': False, 'text': '<pre><code> BitmapCacheOption.OnLoad\n\nvar bmp = await System.Threading.Tasks.Task.Run(() =&gt; \n{ \nBitmapImage img = new BitmapImage(); \nimg.BeginInit(); \nimg.CacheOption = BitmapCacheOption.OnLoad; \nimg.UriSource = new Uri(path); \nimg.EndInit(); \nImageBrush brush = new ImageBrush(img); \n\n}\n</code></pre>\n'}, {'answer_id': 37737445, 'author': 'David', 'author_id': 1995676, 'author_profile': 'https://Stackoverflow.com/users/1995676', 'pm_score': 2, 'selected': False, 'text': '<p>This will allow you to create the BitmapImage on the UI thread by using the HttpClient to do the async downloading:</p>\n\n<pre><code>private async Task&lt;BitmapImage&gt; LoadImage(string url)\n{\n    HttpClient client = new HttpClient();\n\n    try\n    {\n        BitmapImage img = new BitmapImage();\n        img.CacheOption = BitmapCacheOption.OnLoad;\n        img.BeginInit();\n        img.StreamSource = await client.GetStreamAsync(url);\n        img.EndInit();\n        return img;\n    }\n    catch (HttpRequestException)\n    {\n        // the download failed, log error\n        return null;\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/36748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3837/']